Compare commits
262
Commits
25364f8e99
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8453b87290 | ||
|
|
83fe76c506 | ||
|
|
c15b51439e | ||
|
|
a13dbc9710 | ||
|
|
c97a067e0e | ||
|
|
333989eeab | ||
|
|
3033ad83fd | ||
|
|
044a3447f6 | ||
|
|
21a5fc8a52 | ||
|
|
11dffcd695 | ||
|
|
3a2d548610 | ||
|
|
28b3273150 | ||
|
|
14cfa44fc5 | ||
|
|
13a984a84d | ||
|
|
442dc3f04b | ||
|
|
247a7889b9 | ||
|
|
1d4ed39fd2 | ||
|
|
d950fcf70e | ||
|
|
6501b7e9a0 | ||
|
|
486fb500d1 | ||
|
|
77570557db | ||
|
|
fbca38e144 | ||
|
|
6ca7f13779 | ||
|
|
d02fd82ced | ||
|
|
43ee619412 | ||
|
|
87224a1451 | ||
|
|
ec1b0acfad | ||
|
|
3143477a62 | ||
|
|
c3ae5ad949 | ||
|
|
f22313deaf | ||
|
|
d116fcc146 | ||
|
|
94baa89423 | ||
|
|
4b4a1084cb | ||
|
|
22bee28ac7 | ||
|
|
083c9dbf7c | ||
|
|
7fdcac3b55 | ||
|
|
5ea0785be6 | ||
|
|
98b41629e7 | ||
|
|
1c6ccceb12 | ||
|
|
3483797e75 | ||
|
|
7dc804be2b | ||
|
|
46ace501a2 | ||
|
|
23de8c9540 | ||
|
|
c2a3b56aaa | ||
|
|
e1607ddbff | ||
|
|
13f3636b6a | ||
|
|
3e83d63b05 | ||
|
|
f5d4b516ab | ||
|
|
3ff0fd9f1c | ||
|
|
07d864cf64 | ||
|
|
2435abacaf | ||
|
|
d29d603158 | ||
|
|
70157ccfc2 | ||
|
|
f49b422095 | ||
|
|
59ac108c90 | ||
|
|
e0f3d43efb | ||
|
|
4c0c0579f5 | ||
|
|
d1caac86b5 | ||
|
|
d431ee283d | ||
|
|
3a6900d45a | ||
|
|
7d703ea524 | ||
|
|
7bcdf77ef9 | ||
|
|
c8c660e63d | ||
|
|
f58f8b0818 | ||
|
|
862d1d536b | ||
|
|
5b4fdab85c | ||
|
|
a7aefa6fe7 | ||
|
|
d2a27d4a78 | ||
|
|
83c0555e52 | ||
|
|
019ca1342a | ||
|
|
49bf3b140e | ||
|
|
b0537ebe9a | ||
|
|
3df36a9bfb | ||
|
|
98793925ef | ||
|
|
2e083d3bb9 | ||
|
|
4135946cb3 | ||
|
|
3d42ca7241 | ||
|
|
77fa8b8c65 | ||
|
|
0e556d8a43 | ||
|
|
fae621475b | ||
|
|
e54f03cba6 | ||
|
|
921f3d06fb | ||
|
|
259001e419 | ||
|
|
ce8c60d957 | ||
|
|
361cfd7883 | ||
|
|
dba7ea739b | ||
|
|
34d6dda1ab | ||
|
|
7f944d718f | ||
|
|
eae4d34c06 | ||
|
|
ddc88b130b | ||
|
|
00c28ccb76 | ||
|
|
8be7635506 | ||
|
|
b68aff80a6 | ||
|
|
88fc90cc6f | ||
|
|
71d21a45b6 | ||
|
|
480baf762f | ||
|
|
103b182598 | ||
|
|
bd23f41a1d | ||
|
|
9172c1a699 | ||
|
|
fb6d39c68b | ||
|
|
b3dcf356a6 | ||
|
|
459a925e36 | ||
|
|
979b4047dc | ||
|
|
2038b84b72 | ||
|
|
256880899b | ||
|
|
a549942afe | ||
|
|
96d3b40560 | ||
|
|
8dcdcac2a6 | ||
|
|
f7ce85a33e | ||
|
|
4754dbc17b | ||
|
|
7413de9301 | ||
|
|
5939be7b7f | ||
|
|
cc67aebe61 | ||
|
|
b1397fa82e | ||
|
|
d923f41f85 | ||
|
|
18fca28b7c | ||
|
|
5d275c8df7 | ||
|
|
a4e33d7a39 | ||
|
|
54ae8ba153 | ||
|
|
e5a62ca648 | ||
|
|
1b821e1a1e | ||
|
|
35e44f681b | ||
|
|
fc192c9f74 | ||
|
|
8b45bdb361 | ||
|
|
febd741671 | ||
|
|
949cbbe7c0 | ||
|
|
e09ec4ab1d | ||
|
|
aaca82d9d7 | ||
|
|
1e072346a9 | ||
|
|
565484de87 | ||
|
|
05ba138d35 | ||
|
|
807cc4bdfa | ||
|
|
6a10c8ff09 | ||
|
|
247a92a89f | ||
|
|
ba2df8b9fd | ||
|
|
29715ef3d1 | ||
|
|
c7c60a64f2 | ||
|
|
1fa3d70dec | ||
|
|
86dc24ae8a | ||
|
|
bb8aa655a1 | ||
|
|
1c38a94dd0 | ||
|
|
a4d5ed7a93 | ||
|
|
9171e366ee | ||
|
|
9717d8176b | ||
|
|
01007fb6dd | ||
|
|
003f20de19 | ||
|
|
f3d1312a69 | ||
|
|
a9841d92b7 | ||
|
|
64761f38ba | ||
|
|
f6e0ca734f | ||
|
|
06cf054f60 | ||
|
|
32bf9c9297 | ||
|
|
fa25b6ee68 | ||
|
|
8f285acb00 | ||
|
|
2311999e57 | ||
|
|
7d60e54f5a | ||
|
|
ceaaadc49f | ||
|
|
d34c7a21b7 | ||
|
|
30286111a8 | ||
|
|
b6892d13fd | ||
|
|
c2c7244d1a | ||
|
|
9704e0d85a | ||
|
|
c2d29184dd | ||
|
|
dc08a805a8 | ||
|
|
d9c4cd35eb | ||
|
|
19d674ed62 | ||
|
|
a71dd4adb7 | ||
|
|
736451e26f | ||
|
|
5a61b164f6 | ||
|
|
99860dbd13 | ||
|
|
3eb6192a1e | ||
|
|
723d47338e | ||
|
|
529343ce82 | ||
|
|
cad4b49e7c | ||
|
|
b0e33e1606 | ||
|
|
e07da0f8f0 | ||
|
|
72f10917a8 | ||
|
|
5a531fd603 | ||
|
|
c9c6967c9c | ||
|
|
d13c54e3c7 | ||
|
|
d858475ddb | ||
|
|
5155d00d9e | ||
|
|
1a6f82bf6d | ||
|
|
5385f46064 | ||
|
|
cf294a7d2b | ||
|
|
bbc7383d3a | ||
|
|
9800114fc4 | ||
|
|
27bc8a6631 | ||
|
|
0cd9ee7689 | ||
|
|
13f57b2525 | ||
|
|
65a462271c | ||
|
|
bc50ba9136 | ||
|
|
1e9f2dc4fb | ||
|
|
f714782fa4 | ||
|
|
ced066dc01 | ||
|
|
81c6f5fe2f | ||
|
|
1d5b1489be | ||
|
|
fd21067a40 | ||
|
|
644e81d1a3 | ||
|
|
f59c0c3484 | ||
|
|
ed82d0a665 | ||
|
|
751d103f4e | ||
|
|
ac0bcf9012 | ||
|
|
cad1be96da | ||
|
|
f309bd5691 | ||
|
|
d5b0ebf895 | ||
|
|
8db535b889 | ||
|
|
cd7dc7973c | ||
|
|
bddaeb9110 | ||
|
|
9f06304100 | ||
|
|
bee5a5ce89 | ||
|
|
9d362bd568 | ||
|
|
8e09f239c8 | ||
|
|
1d84a40c04 | ||
|
|
39acf22808 | ||
|
|
7162272cc0 | ||
|
|
30fd5a029b | ||
|
|
623dc08875 | ||
|
|
3f86aec0be | ||
|
|
3999c5efc1 | ||
|
|
0873176f64 | ||
|
|
4730d19694 | ||
|
|
dc1570877c | ||
|
|
3ffd13ce6e | ||
|
|
b6df3b7ce7 | ||
|
|
8161c352a0 | ||
|
|
995a0380c3 | ||
|
|
f0e6a8fc19 | ||
|
|
b8ddf14e7d | ||
|
|
01e6f7e2c3 | ||
|
|
2e9afeec0f | ||
|
|
e6dc74df6f | ||
|
|
3280ed71f7 | ||
|
|
e31d1704a2 | ||
|
|
04ef7f44a2 | ||
|
|
1daf762bda | ||
|
|
f8e1107851 | ||
|
|
87e01e260b | ||
|
|
f7c2e35e29 | ||
|
|
37836f8824 | ||
|
|
b891122936 | ||
|
|
8df76d3288 | ||
|
|
93403b4d3a | ||
|
|
ce0df6a126 | ||
|
|
bd72fa75f9 | ||
|
|
178abd4b2d | ||
|
|
0ace776367 | ||
|
|
cb64f7bf65 | ||
|
|
4ca48ac590 | ||
|
|
681f0f95da | ||
|
|
19b81c169d | ||
|
|
57ac1d2cdd | ||
|
|
ea11efe3d1 | ||
|
|
906d1db7d1 | ||
|
|
9789e3d762 | ||
|
|
85b3ef618f | ||
|
|
fa26ec3ec4 | ||
|
|
88527f39b6 | ||
|
|
cb215e2595 | ||
|
|
727b147c81 | ||
|
|
292b9934b1 | ||
|
|
9450831ef3 |
+27
-12
@@ -18,26 +18,41 @@ OPENAI_API_KEY=
|
||||
OPENAI_MODEL=gpt-4o-mini
|
||||
OPENAI_SENTIMENT_BATCH_SIZE=5
|
||||
|
||||
# Fundamentals Provider — Financial Modeling Prep
|
||||
FMP_API_KEY=
|
||||
# Dolt bulk data — local clone of post-no-preference/earnings. Together with the
|
||||
# SEC EDGAR block below this is the ONLY fundamentals source; there is no
|
||||
# provider-API fallback.
|
||||
# DOLT_BINARY: path to the dolt CLI (set the full path in dev if it's not on PATH,
|
||||
# e.g. Windows: C:\Program Files\Dolt\bin\dolt.exe). DOLT_DATA_DIR holds the
|
||||
# clones; in PRODUCTION it MUST be outside the deploy tree (deploy is
|
||||
# rsync --delete) — e.g. /var/lib/signal-platform/dolt. The earnings clone lives
|
||||
# at <DOLT_DATA_DIR>/<DOLT_EARNINGS_SUBDIR>. Production setup is automated by
|
||||
# deploy/provision_fundamentals.sh; see docs/fundamentals-deployment.md.
|
||||
DOLT_BINARY=dolt
|
||||
DOLT_DATA_DIR=dolt-data
|
||||
DOLT_EARNINGS_SUBDIR=earnings
|
||||
# Free-space floor checked before a pull (clone is ~1.7 GB and grows). 5 GB is a
|
||||
# safe production default; lower only on a space-constrained dev box.
|
||||
DOLT_MIN_FREE_DISK_GB=5.0
|
||||
# Hard timeout (s) on each dolt subprocess so a hung pull/sql can't pin the
|
||||
# import connection + advisory lock.
|
||||
DOLT_COMMAND_TIMEOUT_SECONDS=600.0
|
||||
|
||||
# Fundamentals Provider — Finnhub (optional fallback)
|
||||
FINNHUB_API_KEY=
|
||||
# SEC EDGAR (fundamentals, workstream A). SEC fair-access REQUIRES an identifying
|
||||
# User-Agent with a REAL contact email — set it, or requests get 403'd. Stay well
|
||||
# under 10 req/s (spacing below).
|
||||
SEC_USER_AGENT=signal-platform/1.0 (contact: you@example.com)
|
||||
SEC_REQUEST_SPACING_SECONDS=0.2
|
||||
SEC_MAX_RETRIES=4
|
||||
SEC_REQUEST_TIMEOUT_SECONDS=30.0
|
||||
|
||||
# Fundamentals Provider — Alpha Vantage (optional fallback)
|
||||
ALPHA_VANTAGE_API_KEY=
|
||||
|
||||
# Regime Monitor — FRED (VIX + HY credit spreads). Free key: https://fred.stlouisfed.org/docs/api/api_key.html
|
||||
# Optional: without it the VIX (P5) and credit-spread (F2) signals show as n/a.
|
||||
# AI/Tech Risk Monitor — FRED (VIX + HY credit spreads). Free key: https://fred.stlouisfed.org/docs/api/api_key.html
|
||||
# Optional: without it the volatility (V1) and credit (C1) pillars show as n/a.
|
||||
FRED_API_KEY=
|
||||
|
||||
# Scheduled Jobs
|
||||
DATA_COLLECTOR_FREQUENCY=daily
|
||||
SENTIMENT_POLL_INTERVAL_MINUTES=30
|
||||
FUNDAMENTAL_FETCH_FREQUENCY=daily
|
||||
RR_SCAN_FREQUENCY=daily
|
||||
FUNDAMENTAL_RATE_LIMIT_RETRIES=3
|
||||
FUNDAMENTAL_RATE_LIMIT_BACKOFF_SECONDS=15
|
||||
|
||||
# Scoring Defaults
|
||||
DEFAULT_WATCHLIST_AUTO_SIZE=10
|
||||
|
||||
@@ -38,7 +38,10 @@ jobs:
|
||||
python-version: "3.12"
|
||||
cache: "pip"
|
||||
- run: pip install ruff
|
||||
- run: ruff check app/
|
||||
# Whole repo, not just app/: tests/ and scripts/ drifted to 11 findings
|
||||
# while unchecked. Rules are pinned in pyproject.toml, so the unpinned
|
||||
# ruff above cannot change what this enforces.
|
||||
- run: ruff check .
|
||||
|
||||
test:
|
||||
needs: lint
|
||||
|
||||
+20
-1
@@ -17,9 +17,13 @@ build/
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
.claude/settings.local.json
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# Local AI tool metadata
|
||||
mcps/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -35,6 +39,21 @@ alembic/versions/__pycache__/
|
||||
# Generated SSL bundle
|
||||
combined-ca-bundle.pem
|
||||
|
||||
# Dolt local dev clones. Production keeps clones in DOLT_DATA_DIR OUTSIDE the
|
||||
# repo tree (deploy is rsync --delete of the tree); this dir is dev-only.
|
||||
dolt-data/
|
||||
|
||||
# Local research artifacts
|
||||
# Backtest reports in reports/ are tracked: they are the evidence behind the
|
||||
# production baseline in the README. The snapshot DBs they run against are not.
|
||||
backtest_snapshots/
|
||||
reports/backtest-*.json
|
||||
# Rebuildable pickle caches are local accelerators, not decision evidence.
|
||||
reports/*.pkl
|
||||
reports/*.pk1
|
||||
reports/.cache/
|
||||
# Runtime A5 parity bundles are generated on the production server. Research
|
||||
# conclusions belong in docs/research, not as an ever-growing artifact archive.
|
||||
reports/fundamentals-parity/
|
||||
|
||||
# Calibration harness raw-pull cache (Alpaca/FRED); regenerable, not a record.
|
||||
.calib-cache/
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
Third-party data attribution
|
||||
============================
|
||||
|
||||
Earnings calendar and EPS history
|
||||
---------------------------------
|
||||
This application ingests the earnings calendar and EPS surprise history from the
|
||||
public DoltHub repository:
|
||||
|
||||
post-no-preference/earnings
|
||||
https://www.dolthub.com/repositories/post-no-preference/earnings
|
||||
|
||||
Licensed under Creative Commons Attribution-ShareAlike 4.0 International
|
||||
(CC BY-SA 4.0): https://creativecommons.org/licenses/by-sa/4.0/
|
||||
|
||||
Use in this project: private, internal ingestion only. The data is normalized
|
||||
into PostgreSQL (`earnings_events`) — the announcement calendar is aligned to the
|
||||
EPS history via a minimum-cost monotonic pairing, symbols are normalized, and the
|
||||
session field is mapped to bmo/amc/unknown. No public API, bulk export, or
|
||||
redistribution of the data is provided. This attribution and the upstream license
|
||||
are preserved per the CC BY-SA 4.0 terms. Re-review licensing before any public
|
||||
or commercial access.
|
||||
|
||||
The post-no-preference/stocks repository (workstream B) is not used at this time
|
||||
and would be reviewed separately.
|
||||
@@ -1,83 +1,307 @@
|
||||
# Signal Dashboard
|
||||
|
||||
Investing-signal platform for NASDAQ stocks. Surfaces the best trading opportunities through weighted multi-dimensional scoring — technical indicators, support/resistance quality, sentiment, fundamentals, and momentum — with asymmetric risk:reward scanning.
|
||||
Investing-signal platform for US equities. It runs one strategy, and it is a boring one:
|
||||
|
||||
**Philosophy:** Don't predict price. Find the path of least resistance, key S/R zones, and asymmetric R:R setups.
|
||||
> **A long-only cross-sectional momentum book.** Buy the top quintile by beta-adjusted 12-1 month momentum, tilt toward higher volatility, hold at most 15 names, cut at 1.5× ATR, then trail at 3× ATR for up to 30 trading days. After an initial-stop exit, re-enter only after the gate has failed and subsequently qualified again.
|
||||
|
||||
**Philosophy:** don't predict price — rank it. The edge is *relative* strength across the universe, and the discipline is in the exit: cut losers fast, let winners run until the trail catches them.
|
||||
|
||||
**What is NOT the edge — read this before trusting a number on screen.** The composite score, the 5 dimensions, sentiment, fundamentals, and Structural S/R are **display context**, not validated predictors. The Gate Target Ladder is screening machinery that preserves the production setup population; it is not a claim about true market structure. In particular:
|
||||
|
||||
- **The headline "target" is not an exit.** It comes from the internal **Gate Target Ladder** and exists only to compute the R:R and reach-probability used by the activation gate. Human-facing chart S/R is a separate model. The live exit reads neither. Across 472 trades in the current daily gate-reset replay, the exit reasons were **229 initial stop, 147 trailing stop, 96 max hold — and 0 targets.** Honoring the target as a take-profit was tested and *halves CAGR* ([research](docs/research/sr-levels-and-exits.md)).
|
||||
- **The composite score does not select trades.** Residual momentum does.
|
||||
|
||||
Full experiment log — everything tested, kept, and rejected: **[docs/research/](docs/research/README.md)**.
|
||||
|
||||
## The strategy, end to end
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
U["Universe — ~500 tickers<br/>daily OHLCV"] --> M["Residual 12-1 momentum<br/><i>12-month return, skip last month,<br/>beta-adjusted vs SPY</i>"]
|
||||
M --> R["Rank cross-sectionally<br/>into percentiles"]
|
||||
R --> G1{"Top 20%?<br/>percentile ≥ 80"}
|
||||
G1 -->|no| SKIP["Not traded<br/><i>(still scored — the control group)</i>"]
|
||||
G1 -->|yes| S["Build the setup<br/>entry = last close<br/><b>stop = entry − 1.5 × ATR</b><br/>primary = Gate Target Ladder proposal"]
|
||||
|
||||
S --> G2{"Activation gate"}
|
||||
G2 --> G2a["R:R ≥ 2.0 <i>(to the primary gate target)</i>"]
|
||||
G2 --> G2b["touch odds ≥ 20%"]
|
||||
G2 --> G2c["action not NEUTRAL<br/>and matches direction"]
|
||||
G2a & G2b & G2c --> Q{"qualified?"}
|
||||
Q -->|no| SKIP
|
||||
Q -->|yes| RANK["Rank by production score<br/>80% momentum %ile<br/>+ 20% volatility %ile"]
|
||||
|
||||
RANK --> BOOK{"Room in the book?<br/>max 15 positions"}
|
||||
BOOK -->|no| WAIT["Wait for a slot"]
|
||||
BOOK -->|yes| OPEN["OPEN — size at 1% account risk"]
|
||||
|
||||
OPEN --> EXIT{"Exit — whichever comes first"}
|
||||
EXIT --> E1["Initial stop hit<br/>entry − 1.5 × ATR → −1R<br/><b>49% of trades</b>"]
|
||||
EXIT --> E2["Trailing stop hit<br/>highest close − 3 × ATR<br/><i>only binds once price is ~1R up</i><br/><b>31% of trades</b>"]
|
||||
EXIT --> E3["Max hold reached<br/>30 trading days<br/><b>20% of trades</b>"]
|
||||
EXIT -.->|"NEVER"| E4["Gate Target Ladder target<br/><b>0% of trades</b>"]
|
||||
|
||||
E1 --> LOCK["Re-entry locked"]
|
||||
LOCK --> GF{"Later daily scan<br/>fails the gate?"}
|
||||
GF -->|no| LOCK
|
||||
GF -->|yes| GQ{"A subsequent daily scan<br/>qualifies again?"}
|
||||
GQ -->|no| GQ
|
||||
GQ -->|yes| RANK
|
||||
|
||||
style M fill:#1e3a5f,color:#fff
|
||||
style OPEN fill:#1e4d2b,color:#fff
|
||||
style E4 fill:#2a2a2a,color:#888
|
||||
style E1 fill:#4a1f1f,color:#fff
|
||||
style E2 fill:#1e4d2b,color:#fff
|
||||
style LOCK fill:#4a351f,color:#fff
|
||||
```
|
||||
|
||||
**How to read the exit box.** The initial stop is tight (1.5× ATR) and the trail is wide (3× ATR), so the trail sits *below* the initial stop at entry and only takes over once price has advanced roughly 1R. Cut fast when wrong; give room once right. That asymmetry is what produces the right-tailed return profile the strategy depends on — most trades lose a little (win rate 36.2%), a few win big (best trade +12.0R), and *that is why there is no take-profit*.
|
||||
|
||||
**What happens after an initial stop.** The stop always closes the trade and realizes its costs. The ticker is then locked until a successful daily full-universe scan first observes it outside the production gate and a later scan observes a fresh qualification. A continuously qualified ticker therefore cannot generate an immediate duplicate entry. Other exit reasons do not start this reset. See the [daily post-stop re-entry study](docs/research/post-stop-reentry.md).
|
||||
|
||||
**Live timing matters.** The **only** full-universe R:R scan runs near the US close (~15:30 ET), then Telegram alerts fire immediately so manual fills can still hit MOC. Outcome eval runs later (~16:45 ET) after a fresh OHLCV fetch of the final bar. Morning jobs refresh data/sentiment/regime without scanning. Stops closed by earlier same-day intraday outcome evals can get a **same-day** fail observation at the near-close scan — closer to the promoted research `gate_reset` arm than the old morning-scan `strict_gate_reset` analogue. Stops after the bell still need a later day. Same-day fail+qualify cannot unlock: `trade_policy` requires the failure to fall on an earlier America/New_York trading date.
|
||||
|
||||
## How It Works
|
||||
|
||||
Scheduled pipelines turn raw prices into a ranked, gated list of tradeable setups. Everything downstream of OHLCV is recomputed from stored data, so each refresh is cheap and idempotent. Job timing is cron-based and configurable in **Admin → Jobs** (default timezone Europe/Berlin).
|
||||
Scheduled pipelines turn raw prices into a ranked, gated list of tradeable setups. Everything downstream of OHLCV is recomputed from stored data, so each refresh is cheap and idempotent. Job timing is cron-based and configurable in **Admin → Jobs** (default timezone **America/New_York** so the near-close scan tracks the cash close through DST).
|
||||
|
||||
### Daily Load — the full refresh
|
||||
### Price-level architecture: two different jobs
|
||||
|
||||
Once a day (default 07:00). Steps run **in dependency order**, each consuming the previous step's fresh output:
|
||||
The platform deliberately has two price-level components. Calling both of them
|
||||
"S/R" hid an important distinction, so the internal screening component is now
|
||||
named the **Gate Target Ladder (GTL)**.
|
||||
|
||||
1. **OHLCV** — fetch the latest daily bars for every tracked ticker (Alpaca); new tickers backfill ~5 years.
|
||||
2. **Sentiment** — fetch sentiment for the names that matter and are stale (> 5 days): top-pick feeders (residual-momentum leaders with a tradeable long setup), the watchlist, and open paper trades, plus a top-N-by-composite discovery net. Runs *before* the scan so the scan sees fresh sentiment.
|
||||
3. **R:R Scan** — recompute S/R zones, the 5-dimension scores and long/short setups (ATR stops, S/R targets) for every ticker, and attach each ticker's residual 12‑1 momentum activation percentile plus the promoted 80/20 production rank.
|
||||
4. **Outcome Eval** — resolve setups that hit target/stop or expired (default 30 trading days) and auto-close paper trades per the exit policy (default: 3x ATR trail with a 30-trading-day max hold).
|
||||
5. **Market Regime** — recompute the regime index (breadth/trend).
|
||||
6. **Regime Monitor** — observational early-warning snapshot (VIX, credit spreads via FRED); feeds nothing else.
|
||||
| Component | Purpose | Lifetime | Consumed by |
|
||||
|---|---|---|---|
|
||||
| **Structural S/R** | A small set of meaningful support/resistance zones for humans | Persisted as `SRLevel` | Charts and alerts |
|
||||
| **Gate Target Ladder** | A broad set of price proposals that preserves the validated setup screen | Built transiently per scan; never persisted as S/R | Target table, headline R:R and activation gate |
|
||||
|
||||
A failing step is logged; the pipeline continues with the next.
|
||||
```mermaid
|
||||
flowchart TD
|
||||
O["Ticker OHLCV history"] --> SR["Structural S/R detector<br/>volume peaks + prominent pivots + round numbers<br/>rejection and recency strength"]
|
||||
SR --> DB[("Persisted SRLevel rows")]
|
||||
DB --> UI["Charts and alerts"]
|
||||
|
||||
O --> GTL["Gate Target Ladder<br/>20 price-range centers + 5-bar pivots<br/>no volume calculation"]
|
||||
GTL --> TRAFFIC["Score historical price traffic<br/>merge nearby proposals and tag side"]
|
||||
TRAFFIC --> HAS{"Any directional proposal<br/>with R:R ≥ 1.5?"}
|
||||
HAS -->|no| NONE["No setup for that direction"]
|
||||
HAS -->|yes| TARGETS["Build up to 5 target candidates<br/>estimate reach-probability"]
|
||||
TARGETS --> PRIMARY["Headline target<br/>most likely candidate clearing<br/>R:R ≥ 1.5 and probability ≥ 20%"]
|
||||
PRIMARY --> GATE{"Live activation gate<br/>headline R:R ≥ 2.0<br/>probability ≥ 20%<br/>momentum and direction pass?"}
|
||||
GATE -->|no| OBS["Keep as unqualified observation"]
|
||||
GATE -->|yes| BOOK["Eligible for production ranking/book"]
|
||||
BOOK --> EXIT["Exit only by ATR stop/trail<br/>or max hold — never by target"]
|
||||
```
|
||||
|
||||
The Gate Target Ladder works step by step:
|
||||
|
||||
1. Build 20 evenly spaced centers over the ticker's observed high/low range and add unfiltered five-bar swing pivots. Volume is not used.
|
||||
2. Count how often historical bars pass through each proposal, convert that traffic to strength, merge proposals within 0.5%, and label them above/below spot.
|
||||
3. For each direction, require at least one proposal with scanner R:R ≥ 1.5 against the 1.5× ATR initial stop.
|
||||
4. Collapse nearby proposals into target zones, discard unsuitable ATR distances, and retain up to five candidates spanning near to far.
|
||||
5. Estimate each candidate's probability of reaching the target before the stop. The headline target is the most likely candidate with R:R ≥ 1.5 and probability ≥ 20%; if none clears both, the most likely candidate remains headline so a distant lottery target cannot game the gate.
|
||||
6. Apply the separate live activation floor to that headline target: production requires R:R ≥ 2.0 and probability ≥ 20%, plus the momentum/direction rules.
|
||||
7. If traded, ignore the target for exits. The initial ATR stop, 3× ATR trail and maximum hold remain authoritative.
|
||||
|
||||
The ladder is intentionally broad and mechanical. It is not presented as
|
||||
market structure, and its transient negative level IDs must never be stored as
|
||||
chart S/R. The full-period parity run reproduced all 202,765 backtest setup
|
||||
candidates, all 1,086 qualified setups, and the production book exactly
|
||||
(Sharpe 2.03, CAGR 50.0%, max drawdown 21.4%, 321 trades). See the
|
||||
[S/R and Gate Target Ladder research](docs/research/sr-levels-and-exits.md#explicit-gate-target-ladder).
|
||||
|
||||
**Ticker-chart diagnostic.** The optional **GTL traffic** toggle draws a
|
||||
right-edge horizontal profile aligned to the price axis. It borrows the visual
|
||||
grammar of a volume profile, but not its meaning: bar width is relative
|
||||
historical OHLCV-bar crossings at each GTL proposal, not traded volume at that
|
||||
price. Hover a bar to inspect its price, crossing count, strength and source.
|
||||
The violet profile is deliberately distinct from the Structural S/R lines and
|
||||
is off by default; it is a research aid, not another trade overlay.
|
||||
|
||||
Below the chart, the **Production rank** strip makes the current 80/20 ordering
|
||||
snapshot explicit: a blue residual-momentum contribution and amber realized-
|
||||
volatility contribution add to the stored strategy rank, while separate
|
||||
percentile rails show each input. Only momentum carries the live activation-
|
||||
gate marker. These are cross-sectional scan percentiles, not historical chart
|
||||
indicators.
|
||||
|
||||
### Pipelines (America/New_York)
|
||||
|
||||
**Morning** (~02:00 ET) — data and display only, **no** qualifying R:R scan:
|
||||
|
||||
1. **OHLCV** — latest daily bars (Alpaca) plus the SPY benchmark; new tickers backfill ~5 years. A symbol whose bars have been stale for 3 days is probed against SEC for a Form 25/25-NSE/15 and **retired** on a hit (history kept — see *Delisting*).
|
||||
2. **Sentiment** — stale names that matter (top-pick feeders, watchlist, open paper, discovery net). Display context only; the activation gate is price-only.
|
||||
3. **Market Trend (SPY)** + **AI/Tech Risk Monitor** — the SPY trend guard and the v4 risk thermometer; feed no trades.
|
||||
4. **Telegram alerts** — change-driven (risk-quadrant etc.); quiet days stay quiet. Setup alerts still fire on the near-close pipeline after the scan.
|
||||
|
||||
**Near-close** (~15:30 ET Mon–Fri) — the only full-universe qualifying observation:
|
||||
|
||||
1. **OHLCV fetch** — refresh the in-progress day-t bar (same path as intraday).
|
||||
2. **R:R Scan** — Structural S/R, scores, Gate Target Ladder setups, residual 12‑1 + 80/20 rank. Advances post-stop gate-reset transitions; failed scans never count.
|
||||
3. **Shadow book** — opt-in automated book; opens top-ranked qualified setups up to capacity at the same near-close prices. Only accepts a scan from this same pipeline run.
|
||||
4. **Telegram alerts** — chained immediately so manual MOC fills can still hit ~15:50/15:55.
|
||||
|
||||
**After close** (~16:45 ET Mon–Fri):
|
||||
|
||||
1. **OHLCV fetch** — final bar (not the partial near-close bar).
|
||||
2. **Outcome Eval** — resolve setups and auto-close paper trades (default 3× ATR trail, 30-day max hold).
|
||||
|
||||
A failing step is logged; the pipeline continues with the next. Near-close duration is logged; warn if > 10 minutes.
|
||||
|
||||
### Intraday — light refresh
|
||||
|
||||
Hourly across the US session (Mon–Fri): only **OHLCV → Outcome Eval**, to keep prices current and close paper trades intraday. No scan/sentiment — the dashboard recomputes live R:R from the latest price, so fresh prices are enough.
|
||||
Hourly mid-session (Mon–Fri ~10:00–15:00 ET): only **OHLCV → Outcome Eval**, to keep prices current and close paper trades intraday. No scan/sentiment — the dashboard recomputes live R:R from the latest price.
|
||||
|
||||
### Other jobs
|
||||
|
||||
Fundamentals (weekly, early Monday) · Alerts (hourly, Telegram) · Backtest (weekly) · Ticker-universe sync (daily). Deep history backfill and event study are manual-only (Admin → Jobs).
|
||||
Dolt earnings import (daily 02:30 ET) · SEC fundamentals import (daily 04:00 ET, also refreshes the fundamentals cache scoring reads) · Backtest (weekly) · Ticker-universe sync (daily). Alerts auto-fire only via the near-close pipeline (still manually triggerable). Deep history backfill and event study are manual-only (Admin → Jobs).
|
||||
|
||||
The SEC import defers a run rather than writing partial data when a filing's XBRL
|
||||
hasn't landed. Two bounds keep that from compounding: `MISSING_XBRL_RETRY_DAYS`
|
||||
caps how long *one* filing blocks promotion, and `PROMOTION_CEILING_DAYS` (7)
|
||||
caps how long the import as a whole can stay deferred — past the ceiling every
|
||||
unresolved filing is aged out in place so `promote()` queues it as a gap row,
|
||||
`source_max_date` advances, and the import self-heals. A `deferred_stale` alert
|
||||
inside that window is normal and clears on its own; check `source_max_date` in
|
||||
`data_import_runs` before diagnosing a wedge.
|
||||
|
||||
### Delisting, not deletion
|
||||
|
||||
Retiring a symbol used to mean `delete_ticker` or a pruning universe bootstrap,
|
||||
both of which cascade through OHLCV, setups and scores. That destroys exactly the
|
||||
history four research documents apologise for: today's tracked universe projected
|
||||
backward is survivorship-biased, and hard-deleting every delisted name is what
|
||||
causes it. Keeping the rows preserves the option to fix that later (it does not
|
||||
fix it — the replay still has to model a delisting as an exit event).
|
||||
|
||||
`tickers` therefore carries `delisted_on` / `delisted_reason` (migration 032);
|
||||
`NULL` means actively traded. The filter is **opt-in** via
|
||||
`ticker_service.active_only`, applied to the live path only — scanner, momentum
|
||||
ranking, scoring, breadth, fundamentals candidates, SEC universe, earnings import,
|
||||
ingestion. The registry and admin views deliberately keep delisted rows visible,
|
||||
and `run_backtest` keeps them on purpose. Detection runs off OHLCV staleness
|
||||
(not the SEC fundamentals import, which stalls for days on unrelated Company-Facts
|
||||
gaps) and retires only on a Form 25/25-NSE/15 hit, so a halt or a rename keeps the
|
||||
existing warning instead. `delisted_on` is the *effective* date — Rule 12d2-2
|
||||
makes a Form 25 removal take effect ten days after filing, so a symbol filed today
|
||||
keeps trading (and keeps qualifying) until that date. It is safe to automate
|
||||
because it is reversible: `clear_delisted` un-retires a false positive, where a
|
||||
delete had already taken the history.
|
||||
|
||||
### From score to "top pick"
|
||||
|
||||
1. **Composite score** — technical, S/R-quality, sentiment, fundamental and momentum sub-scores (0–100) combine into a weighted composite (weights configurable; missing dimensions re-normalize).
|
||||
2. **Setups** — the scanner builds long/short setups with ATR stops and S/R targets, then adds a confidence score, conflict flags and a target reach-probability.
|
||||
3. **Activation gate** — a setup *qualifies* only if it clears the R:R floor **and** ranks in the top residual-momentum percentile of the universe (the validated edge is long-only; the confidence floor was ablated to zero effect and defaults off).
|
||||
1. **Composite score** — technical, S/R-quality, sentiment, fundamental and momentum sub-scores (0–100) combine into a weighted composite (weights configurable; missing dimensions re-normalize). **Display and ranking only — it does not select trades.**
|
||||
2. **Setups** — the scanner builds long/short setups with a 1.5× ATR stop, generates up to five candidates from the transient Gate Target Ladder, and makes the most likely worthwhile candidate the headline target. It then adds confidence and conflict context plus a per-target reach-probability.
|
||||
3. **Activation gate** — a setup *qualifies* only if it ranks in the top residual-momentum percentile of the universe (**the actual selection**, long-only), its headline target clears the live R:R floor, **and** that target carries at least a 20% reach-probability. The confidence floor was ablated to zero effect and defaults off.
|
||||
4. **Top pick** — qualified setups are ordered by the production rank: 80% residual momentum percentile + 20% 6-month realized-volatility percentile. The #1 is highlighted on the Dashboard and labelled on the ticker page.
|
||||
|
||||
**What the R:R and reach-probability in step 3 actually are.** They are *gate inputs*, computed from a Gate Target Ladder proposal the trade will never exit at — they exist to filter setups, not to forecast the trade you're about to take. A setup with "R:R 2.4:1, 34% reach probability" is not a claim that you'll make 2.4R with 34% probability; it's a claim that this setup cleared the screen. What actually happens to a trade is in the exit box of the diagram above, and on the "what usually happens" panel in the UI. Conflating the two is the single easiest way to misread this app.
|
||||
|
||||
### Two books: shadow (automated) and discretionary (manual)
|
||||
|
||||
The platform keeps **two** paper books, and the difference between them is the
|
||||
whole point.
|
||||
|
||||
| Book | Who selects | What it measures |
|
||||
|---|---|---|
|
||||
| **Shadow book** (`app/services/shadow_book_service.py`) | The machine — top-ranked qualified setups up to capacity, every near-close scan | The **strategy**, faithfully |
|
||||
| **Discretionary book** | You, by clicking "paper trade" on a setup | The strategy **plus** your discretion and availability |
|
||||
|
||||
The manual book only ever contains trades the user chose to take, inside a ~20
|
||||
minute window, on days they were around. The backtest that validated this
|
||||
strategy does none of that, which makes the manual record unusable on its own as
|
||||
out-of-sample evidence. The shadow book closes that gap: it mirrors
|
||||
`_simulate_portfolio`'s selection rule exactly, orders on the *stored*
|
||||
`strategy_rank` the scanner already wrote (so the two cannot drift apart) and
|
||||
shares the manual book's exit policy — the only difference between the books is
|
||||
*which* qualified setups get taken.
|
||||
|
||||
It runs as a step of the near-close pipeline, straight after the scan so entries
|
||||
mark at the same near-close prices, and it only accepts a scan from the same
|
||||
pipeline run. It is **opt-in** (`shadow_book_enabled`, with capacity, risk % and
|
||||
starting equity under **Admin → Settings → Performance & Shadow Book**) because it
|
||||
writes live trades. The **Dashboard**'s performance chart plots shadow vs
|
||||
discretionary vs SPY; *Signals → Paper Trades* still shows the discretionary book
|
||||
only.
|
||||
|
||||
## Strategy Status — What's Validated and What Isn't
|
||||
|
||||
**Read this before touching scoring, gating, or setup logic.** The platform measures itself — a weekly-replay backtest plus a factor rank-IC harness (`app/services/backtest_service.py`) — and the verdicts below come from those reports (June 2026, ~5 years of OHLCV), not from opinion.
|
||||
**Read this before touching scoring, gating, or setup logic.** The platform measures itself — a weekly-replay backtest plus a factor rank-IC harness (`app/services/backtest_service.py`) — and the verdicts below come from those reports (latest run July 2026, ~5 years of OHLCV), not from opinion.
|
||||
|
||||
> **The full experiment log lives in [docs/research/](docs/research/README.md)** — every strategy we've tested, the result, and the decision. Check it before proposing an idea; most of the obvious ones have already been run and rejected.
|
||||
|
||||
| Component | Verdict | Evidence |
|
||||
|---|---|---|
|
||||
| **Residual 12-1 cross-sectional momentum** (the activation gate, long-only) | **Production gate — in-sample edge** | Promoted July 2026 after the portfolio variant beat raw 80 on CAGR, Sharpe and drawdown. Raw 12-1 remains a fallback only when benchmark data is unavailable |
|
||||
| S/R setup engine (ATR stops, S/R targets, reach-probability) | **Filter/execution context, not the exit** | R:R/room-to-run still earns its keep as a filter, but S/R targets underperform the time exit. The probability model is display-only |
|
||||
| **3× ATR trailing exit** (+ 1.5× ATR initial stop, 30-day max hold) | **Production exit — best Sharpe of every exit tested** | Beat hold / SMA50 / 20-day-low / technical-40 and both take-profit variants (July 2026) |
|
||||
| **Post-stop gate reset** | **Production re-entry policy** | The initial stop always closes; the ticker must later fail the daily gate and subsequently qualify again. At the then-production capacity of 10: Sharpe 1.67 → 1.77, CAGR 45.2% → 48.3%, DD 24.3% → 21.6% versus immediate re-entry. Capacity has since been raised to 15 — see the open question under the re-entry section. [Full study](docs/research/post-stop-reentry.md) |
|
||||
| **Book capacity 15** (raised from 10, 2026-08-05) | **Production sizing** | The focused daily capacity bracket found the count cap was binding and cost real compounding: +1.075pp CAGR paired, 51 paths better / 2 worse, drawdown unchanged. Cash plus the 20% notional cap saturates the book near 12, so the cap no longer binds. [Findings](docs/research/portfolio-capacity-bracket-findings.md#correction-2026-08-05-ev-per-trade-was-the-wrong-lens) |
|
||||
| **Structural S/R** | **Human-facing context only — not a gate and not an exit** | Clean, capped zones are persisted for charts and alerts. The scanner deliberately does not read them. |
|
||||
| **Gate Target Ladder** | **Gate input only — not market structure and not an exit** | Volume-free range grid + pivots preserves the useful legacy screening behavior exactly: 1,086/1,086 qualified setups retained and identical Sharpe 2.03 / CAGR 50.0% / DD 21.4% / 321 trades. The exit never reads its target. [Full write-up](docs/research/sr-levels-and-exits.md#explicit-gate-target-ladder) |
|
||||
| Composite score + 5 dimensions | **Display/ranking only** | Sub-scores are hand-built heuristics; none has a measured IC. Note: the "momentum" *dimension* is 5/20-day ROC — NOT the validated 12-1 factor (that lives in `momentum_service`) |
|
||||
| LLM sentiment | Display + a bounded composite adjustment (± weight × 100 pts around neutral 50) | Deliberately kept out of the setup engine; no point-in-time history to validate against yet |
|
||||
| Fundamentals | Feeds composite + confidence only | Latest values only, no history — same limitation |
|
||||
| Short setups | **Excluded while the momentum gate is active** | Backtest showed shorts fight the trend and drag expectancy |
|
||||
| Expected-value gate (removed June 2026) | Degenerate — do not resurrect | Structurally favored distant lottery targets; selected *worse*-than-random setups |
|
||||
| Expected-value gate (removed June 2026) | Degenerate — do not resurrect | Structurally favored distant lottery targets; selected *worse*-than-random setups. Orphaned settings dropped in migration 020 |
|
||||
| Gate target as a take-profit (tested July 2026) | **Rejected** | Sharpe 2.04 → 1.47, CAGR halved. Win rate *rose* — it truncates the right tail where the edge lives |
|
||||
| "Clear-air" gate relaxation (tested July 2026) | **Rejected — failed out-of-sample** | Strictly better in-sample (Sharpe 2.07 / CAGR 62.3% / DD 20.1%), then lost on a real train/test split (Sharpe 2.78 → 2.45). A cautionary tale: nested lookbacks are not OOS |
|
||||
|
||||
Caveats on the momentum result: in-sample, roughly one market regime, costs/slippage approximated at 0.1% per side, and residual momentum still needs SPY benchmark history to compute. The **out-of-sample proof is the forward paper-trade record**: Signals → Track Record compares live qualified expectancy against the backtest.
|
||||
Caveats on the momentum result: in-sample, roughly one market regime, costs/slippage approximated at 0.1% per side, and residual momentum still needs SPY benchmark history to compute. The **out-of-sample proof is the forward record of the shadow book** — the automated twin that takes every top-ranked qualified setup, with no discretion or availability mixed in. The Dashboard chart tracks it against the discretionary book and SPY; *Signals → Backtest* is what it is being compared against.
|
||||
|
||||
### Current production baseline
|
||||
### Daily post-stop re-entry decision (2026-07-17)
|
||||
|
||||
Use this as a regression guardrail for future strategy changes, not as a return promise. Backtest run: local production SQLite snapshot, 506 tickers, weekly cadence, 30-trading-day horizon, 2022-06-28 → 2026-07-01, 0.1% per-side costs, price-only SPY benchmark.
|
||||
The production policy is **normal gate reset**, evaluated with daily setup opportunities and live-like full-universe ranking. An initial stop always closes. Re-entry unlocks only after a later successful daily scan observes the ticker failing the gate and a subsequent scan observes it qualifying again. The study replayed 1,011,248 point-in-time candidate observations across 505 tickers from 2022-06-24 through 2026-07-02, with the production GTL gate, 80/20 rank, exit, fees, sizing, and 10-position capacity.
|
||||
|
||||
| Item | Current baseline |
|
||||
| Re-entry policy | Total return | CAGR | Max DD | Sharpe | Trades |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| Immediate | 348.4% | 45.2% | -24.3% | 1.67 | 489 |
|
||||
| **Gate reset (selected study arm)** | **388.1%** | **48.3%** | **-21.6%** | **1.77** | **472** |
|
||||
| Strict gate reset (live timing analogue) | 342.7% | 44.8% | -23.4% | 1.68 | 471 |
|
||||
| Fixed five-session cooldown | 250.8% | 36.6% | -22.2% | 1.47 | 473 |
|
||||
|
||||
In the disjoint 2025+ book, gate reset also beat immediate re-entry (Sharpe 1.66 vs 1.55; CAGR 41.8% vs 39.3%) and the fixed five-session rule (Sharpe 1.43; CAGR 32.7%). Its lead over both survived costs of 0.2% and 0.3% per side. The result is capacity-specific: cooldown 5 won at capacity 5, while immediate had slightly higher return and Sharpe at capacity 15.
|
||||
|
||||
> **Open question (since 2026-08-05).** This study was run — and gate reset promoted — at capacity 10. Production capacity was subsequently raised to 15, which is the one capacity in the matrix where *immediate* re-entry edged ahead. The re-entry policy is therefore currently running outside the portfolio it was validated on. Nothing else changed, and the two arms differed only modestly, but the matrix should be rerun at capacity 15 before treating gate reset as settled. Until then, keep gate reset (the incumbent) rather than switching on an untested read.
|
||||
|
||||
Those promotion numbers belong to the selected normal-reset study arm. Under the **pre-cutover** morning-scan scheduler (scan always before any outcome eval), live first-observation timing matched the stricter `strict_gate_reset` analogue (full-period Sharpe 1.68 / CAGR 44.8% / DD 23.4%). After the **near-close cutover** (2026-07), stops closed by earlier same-day intraday evals can receive a same-day fail observation at ~15:30 ET — moving live behavior **toward** the promoted `gate_reset` arm. Requalification still requires a later America/New_York trading date than the failure (`trade_policy` distinct-day guard). Full definitions and all nine policy arms: [docs/research/post-stop-reentry.md](docs/research/post-stop-reentry.md); execution evidence: [docs/research/execution-recovery.md](docs/research/execution-recovery.md).
|
||||
|
||||
`gate_reset` and a simple `next_session` block happened to produce the same executed live-universe portfolio in this sample. Their rules are still different: this establishes that same-day re-entry was harmful here, but does not isolate a separate historical return premium from the reset condition. Gate reset was promoted because it represents a genuinely new signal episode and did not sacrifice results in the production book. Full definitions, all nine policy arms, cost/capacity sensitivity, and legacy-rank results are in [docs/research/post-stop-reentry.md](docs/research/post-stop-reentry.md); source report: [`reports/daily_reentry_matrix.json`](reports/daily_reentry_matrix.json).
|
||||
|
||||
### Historical weekly production baseline (pre gate-reset)
|
||||
|
||||
Use this as the historical ranking/exit regression guardrail, not as a return promise or the current re-entry-policy result. This run predates the post-stop gate reset **and the 2026-08-05 capacity raise to 15**, and uses weekly entry replay, so its portfolio headline is not directly comparable with the daily matrix above. Backtest run: local production SQLite snapshot, 506 tickers, weekly cadence, 30-trading-day horizon, 2022-06-28 → 2026-07-02, 0.1% per-side costs, price-only SPY benchmark. Numbers below are the 2026-07-11 run (`reports/backtest-20260711-prod-baseline.json`) — measured *after* the primary-target probability floor shipped, which pruned lottery-target setups (1,428 → 1,089 qualified) and lifted Sharpe on all three promotion contenders.
|
||||
|
||||
| Item | Historical weekly baseline |
|
||||
|---|---|
|
||||
| Strategy version | `residual_highvol_80_20_atr_trail3_v1` |
|
||||
| Production gate | Long-only, residual 12-1 momentum percentile >= 80, R:R floor on, NEUTRAL excluded, confidence floor effectively off |
|
||||
| Production gate | Long-only, residual 12-1 momentum percentile >= 80, headline gate-target R:R >= 2.0 (live `activation_min_rr`; code default 2.0), primary-target reach-probability >= 20%, NEUTRAL excluded, confidence floor off (0) |
|
||||
| Production rank | 80% residual momentum percentile + 20% 6-month realized-volatility percentile |
|
||||
| Exit | Initial ATR stop plus 3x ATR trailing stop, max 30 trading days |
|
||||
| Portfolio CAGR | +44.4% |
|
||||
| Portfolio total return | +336.6% vs SPY +95.7% |
|
||||
| Max drawdown | -23.8% |
|
||||
| Sharpe | 1.72 daily, annualized |
|
||||
| Trades | 376 |
|
||||
| Average hold | 14.7 trading days |
|
||||
| Portfolio CAGR | +50.4% |
|
||||
| Portfolio total return | +413.8% vs SPY +95.7% |
|
||||
| Max drawdown | -21.4% |
|
||||
| Sharpe | 2.04 daily, annualized |
|
||||
| Trades | 320 |
|
||||
| Win rate | 37.5% |
|
||||
| Average hold | 15.3 trading days |
|
||||
| Best / worst trade | +12.9R / -3.3R |
|
||||
| **How trades actually ended** | **initial stop 144 (45%) · trailing stop 98 (31%) · max hold 78 (24%) · target 0 (0%)** |
|
||||
|
||||
That last row is the strategy in one line: a 37.5% win rate is *fine* because the +12.9R tail pays for every −1R stop. It is also why no take-profit exists — and why the S/R "target" shown in the UI is a screening artifact, not a plan.
|
||||
|
||||
Promotion evidence from the same snapshot:
|
||||
|
||||
| Candidate | CAGR | Max DD | Sharpe | Trades | Read |
|
||||
|---|---:|---:|---:|---:|---|
|
||||
| Legacy residual 80 + 30d hold | +34.8% | -24.4% | 1.51 | 339 | Previous production baseline |
|
||||
| Residual/high-vol 80/20 + 30d hold | +39.2% | -23.9% | 1.55 | 345 | Better entry rank, slightly lower drawdown |
|
||||
| Residual/high-vol 80/20 + 3x ATR trail | +44.4% | -23.8% | 1.72 | 376 | Promoted: better CAGR, Sharpe, and drawdown |
|
||||
| Pure high-vol 80 + 30d hold | +37.7% | -37.6% | 1.22 | 491 | Rejected: standalone volatility was too volatile |
|
||||
| Low-vol 80 + 30d hold | +0.4% | -23.1% | 0.09 | 257 | Rejected: no useful edge |
|
||||
| Legacy residual 80 + 30d hold | +49.6% | -15.8% | 2.02 | 300 | Previous production baseline. Still the shallowest drawdown of the three |
|
||||
| Residual/high-vol 80/20 + 30d hold | +51.9% | -22.2% | 2.00 | 303 | The vol tilt buys CAGR and pays for it in drawdown |
|
||||
| Residual/high-vol 80/20 + 3x ATR trail | +50.4% | -21.4% | 2.04 | 320 | Promoted: best Sharpe. The ATR trail recovers part of the drawdown the vol tilt costs |
|
||||
| Pure high-vol 80 + 30d hold | +31.6% | -34.8% | 1.12 | 476 | Rejected: standalone volatility was too volatile |
|
||||
| Low-vol 80 + 30d hold | +2.7% | -19.5% | 0.29 | 240 | Rejected: no useful edge |
|
||||
|
||||
Read the top three honestly: the production book wins on Sharpe, not on every axis. The 80/20 vol tilt buys ~2pp of CAGR over the legacy residual-only book but costs ~6pp of drawdown, and the ATR trail hands part of that drawdown back. If drawdown ever matters more than risk-adjusted return here, legacy residual 80 + hold is the row to revisit.
|
||||
|
||||
The conclusion is not "trade high volatility alone." Keep residual momentum as the entry gate, use realized volatility only as a small ranking tilt, and add the ATR trail as defensive exit discipline.
|
||||
|
||||
@@ -87,42 +311,46 @@ Parity guard (July 2026): the portfolio monitor's **Production** row replays the
|
||||
|
||||
### Tuned and confirmed — do not retest without new data (July 2026)
|
||||
|
||||
A systematic single-variable sweep (offline prod snapshot, production gate/rank/exit, 2022-06 → 2026-07 plus disjoint 2022–23 / 2024–26 folds) confirmed **every** production setting. Retesting these against the same ~4-year snapshot is wasted compute and invites overfitting; revisit only with meaningfully new data (longer history or broader universe).
|
||||
A systematic single-variable sweep (offline prod snapshot, production gate/rank/exit, 2022-06 → 2026-07 plus disjoint 2022–23 / 2024–26 folds) confirmed every production setting **except book size**, which a later focused bracket reversed (see the row below). Retesting these against the same ~4-year snapshot is wasted compute and invites overfitting; revisit only with meaningfully new data (longer history or broader universe) — or, as with capacity, a demonstrably better measurement lens.
|
||||
|
||||
| Knob tested | Verdict | Evidence |
|
||||
|---|---|---|
|
||||
| ATR trail multiple {1.5–4.0} | **Keep 3.0** | Return+Sharpe peak; ≤2.0 whipsaws out the momentum right tail; ≥2.5 is a plateau |
|
||||
| SPY 200d-MA regime overlay (block entries / go flat) | **Reject** | Halves return (315%→138%) with zero drawdown benefit — the ATR trail already manages downside, and the filter blocks the recovery-phase entries that make the money |
|
||||
| Momentum lookback: 6-1, 3-1, 12-7 (Novy-Marx), composites | **Keep residual 12-1** | 6-1/3-1 rank-IC ≈ 0; 12-7 IC 0.045 / t 1.58 — weaker than residual 12-1 (0.055 / t 1.98) |
|
||||
| Selection cutoff {70, 75, 85, 90} × book size {10, 15, 20} | **Keep 80 × 10** | Monotonically worse in both directions from 80; the 10-slot cap never binds (<10 concurrent) |
|
||||
| Selection cutoff {70, 75, 85, 90} × book size {10, 15, 20} | **Keep cutoff 80; book size raised to 15 (2026-08-05)** | The cutoff is monotonically worse in both directions from 80. The book-size half of this row was **reversed**: the weekly replay's "the 10-slot cap never binds" read came from EV per trade, which is the wrong lens for anything that changes trade *count*. The focused daily bracket found cap 10 *was* binding and cost +1.075pp CAGR; at 15 the cap never bound in any cell (max observed 12 concurrent, zero full-book skips) |
|
||||
| Position sizing: equal-weight, inverse-vol, risk-% sweep | **Keep 1% fixed-fractional** | See the inverse-vol warning below |
|
||||
| Post-stop re-entry: immediate, fixed 2–5 sessions, gate resets, confirmation filters | **Keep normal gate reset** — but measured at capacity 10, and capacity is now 15 | Sharpe 1.77 vs 1.67 immediate and 1.47 cooldown 5. The "rerun before changing portfolio capacity" caveat is now outstanding — see the open question above |
|
||||
| FIP path-smoothness as an in-book tie-breaker/filter | **Reject** (but see the lead below) | Non-monotonic across FIP quintiles within the qualified set; either half of a median split underperforms the full book — thinning the entry stream costs more compounding than the tilt returns |
|
||||
|
||||
Two findings future sessions must not re-litigate:
|
||||
|
||||
- **The "inverse-vol sizing win" (July 2026) was mis-attributed — do not resurrect.** The diagnostic sized `notional = equity × 1% / vol_6m`, and the 20% notional cap bound on 95% of entries, so it actually measured "~5 positions × 20% notional each" — a concentration/risk-appetite bump economically equivalent to raising risk to 1.5%, not vol-managed sizing. Genuine inverse-vol sizing (risk budget × median-vol/vol) cuts max drawdown to −18.2% but costs ~58pp total return at flat Sharpe: a risk-preference trade, not edge.
|
||||
- **`fip_id` — Da/Gurun/Warachka information discreteness over the 12-1 formation window — is the strongest cross-sectional signal measured on this universe: IC −0.045, t = −2.91, correct sign (continuous-information winners outperform).** It clears the iron-rule bar in isolation but does not improve this book (the momentum gate already captures the effect in-sample). It is the prime ranking/gate candidate **if the universe broadens** (e.g. `nasdaq_all`).
|
||||
- **`fip_id` — Da/Gurun/Warachka information discreteness over the 12-1 formation window — is the strongest cross-sectional signal on the *production* universe: IC −0.045, t = −2.91, correct sign (continuous-information winners outperform).** It clears the iron-rule bar in isolation but does not improve this book (the momentum gate already captures the effect in-sample). **Phase B (liquid-1500, research branch only):** unconditional fip fails iron rule (−0.017 / t −1.85); mom-conditional fip (−0.088 / t −4.58) is a *book-tilt candidate only* after a baseline breadth mom book is proven. Do **not** cite the orphaned 21:14 row (+0.0575) — it raced a partial `research.sqlite`. See `docs/research/fip-breadth-ic.md`.
|
||||
|
||||
### The iron rule for strategy changes
|
||||
|
||||
A signal earns its way into selection **only** through the factor harness:
|
||||
|
||||
1. Add it as a point-in-time function of past bars in `_signal_values()` (`backtest_service.py`).
|
||||
2. Run the backtest (Admin → Jobs, or the weekly run) and read the **Signal edge** table (Signals → Track Record).
|
||||
2. Run the backtest (Admin → Jobs, or the weekly run) and read the report's `signal_eval` section. This one is **local-report only** — the deployed Backtest tab does not render it (see *Reading a local backtest report* below).
|
||||
3. Wire it into the gate or ranking **only if** |mean IC| ≳ 0.03 with a consistent sign and `reliable: true` (≥ 12 non-overlapping windows).
|
||||
|
||||
Corollaries: never let an unvalidated score gate setups; the outcome evaluator must keep scoring **all** setups (unqualified ones are the control group); LLM output stays display-only in the quant path.
|
||||
|
||||
### Highest-value next experiments (in order)
|
||||
|
||||
1. **Forward monitor the promoted strategy** — the production UI now behaves like a portfolio monitor for the current strategy, with selectable lookbacks and SPY comparison. Forward paper-trade months are the only evidence the snapshot cannot provide; the July 2026 tuning pass closed every in-sample lead. (Trailing-stop sensitivity and the max-15 capacity check are done — see the tuning table above.)
|
||||
> Check **[docs/research/](docs/research/README.md)** first — 13 strategy ideas have already been tested and rejected, including the obvious ones (take-profit exits, regime overlays, inverse-vol sizing, shorts, sector-residual momentum).
|
||||
|
||||
1. **Forward monitor the promoted strategy** — *Signals → Backtest* behaves like a portfolio monitor for the current strategy, with selectable lookbacks and SPY comparison, and the Dashboard chart carries the forward record. Forward months of the **shadow book** are the only evidence the snapshot cannot provide; the July 2026 tuning pass closed every in-sample lead. (Trailing-stop sensitivity and the capacity bracket are done — capacity was raised to 15.)
|
||||
2. **Signal context snapshots** — accumulate point-in-time composite/sentiment/fundamental context for every new setup so the discretionary overlay can be tested forward-only.
|
||||
3. **More breadth, not more history** — widening the ranked universe (e.g. `nasdaq_all`) strengthens each week's cross-section and the IC t-stat, even if only the top slice is traded. Now doubly motivated: it is also where the strong `fip_id` signal (see tuning findings) could become tradeable. (Deeper history was considered and declined.)
|
||||
3. **Breadth is no longer free leverage** — Phase B found residual-mom t-stat *fell* on liquid-1500 vs the 505-name fingerprint (0.055/1.98 → 0.029/1.33). Any breadth book must clear a pre-registered baseline arm before fip tilts mean anything. (Deeper history was considered and declined.)
|
||||
|
||||
## Key Use Cases
|
||||
|
||||
- **Find today's best long setup.** On the **Dashboard**, the *Top Setups* table lists residual-gated qualified setups ranked by the production 80/20 residual/high-vol score, with the #1 flagged "Top pick". Each row opens the ticker page for the chart, scores, S/R targets and entry/stop.
|
||||
- **Track a trade you took.** Mark a setup as a **paper trade**: it's marked-to-market against the latest close, auto-closed by the active exit policy (default: 3x ATR trail with a 30-trading-day max hold), and its sentiment stays fresh while open. *Signals → Track Record* shows the realized edge.
|
||||
- **Find today's best long setup.** On the **Dashboard**, the *Top Setups* table lists residual-gated qualified setups ranked by the production 80/20 residual/high-vol score, with the #1 flagged "Top pick". Each row opens the ticker page for its chart, Structural S/R, Gate Target Ladder targets and entry/stop.
|
||||
- **Track a trade you took.** Mark a setup as a **paper trade**: it's marked-to-market against the latest close, auto-closed by the active exit policy (default: 3x ATR trail with a 30-trading-day max hold), and its sentiment stays fresh while open. *Signals → Paper Trades* shows the realized edge of your discretionary book; the Dashboard chart puts it next to the automated shadow book and SPY.
|
||||
- **Ask whether the strategy is worth trading at all.** *Signals → Backtest* replays the promoted strategy over history — portfolio monitor vs SPY over selectable lookbacks, headline risk-adjusted metrics (Sharpe, Sortino, Gain-to-Pain, dollar profit factor) and the report's own recommendation — with the live-outcome evaluation panel underneath it.
|
||||
|
||||
## Stack
|
||||
|
||||
@@ -137,24 +365,27 @@ Corollaries: never let an unvalidated score gate setups; the outcome evaluator m
|
||||
| Charts | Canvas 2D candlestick chart with S/R overlays |
|
||||
| Routing | React Router v6 (SPA) |
|
||||
| HTTP | Axios with JWT interceptor |
|
||||
| Data providers | Alpaca (OHLCV); OpenAI / Gemini / DeepSeek / xAI (sentiment, pluggable); Fundamentals chain: FMP → Finnhub → Alpha Vantage; FRED (regime); Telegram (alerts) |
|
||||
| Data providers | Alpaca (OHLCV); OpenAI / Gemini / DeepSeek / xAI (sentiment, pluggable); SEC EDGAR Company Facts + DoltHub earnings (fundamentals, bulk import); FRED (regime); Telegram (alerts) |
|
||||
|
||||
## Features
|
||||
|
||||
### Backend
|
||||
- Ticker registry with full cascade delete
|
||||
- Universe bootstrap for `sp500`, `nasdaq100`, `nasdaq_all` via admin endpoint
|
||||
- Ticker registry with reversible delisting (history preserved) plus an explicit cascade delete
|
||||
- Universe bootstrap for `sp500`, `nasdaq100`, `nasdaq_all` via admin endpoint — free public sources (Wikipedia / NASDAQ Trader), then the cached snapshot, then a built-in seed list. The seeds are representative, not complete, so a *fresh* install bootstrapped while the public source is unreachable gets a partial universe; a warm instance falls through to its cache.
|
||||
- OHLCV price storage with upsert and validation
|
||||
- Technical indicators: ADX, EMA, RSI, ATR, Volume Profile, Pivot Points, EMA Cross
|
||||
- Support/Resistance detection with strength scoring and merge-within-tolerance
|
||||
- Structural Support/Resistance detection with rejection/recency strength, ATR-adaptive merging and a hard cap; persisted for charts and alerts
|
||||
- Transient Gate Target Ladder — volume-free range grid plus pivots, used only for nominal targets, reach-probability and gate R:R
|
||||
- Sentiment analysis with time-decay weighted scoring
|
||||
- Fundamental data tracking (P/E, revenue growth, earnings surprise, market cap)
|
||||
- 5-dimension scoring engine (technical, S/R quality, sentiment, fundamental, momentum) with configurable weights
|
||||
- Risk:Reward scanner — long and short setups, ATR-based stops, S/R-based targets, configurable R:R threshold (default 1.5:1)
|
||||
- Activation gate — qualifies setups on a residual-momentum percentile floor plus an R:R floor (validated long-only edge)
|
||||
- Risk:Reward scanner — long and short setups, 1.5x ATR stops, Gate Target Ladder nominal targets, configurable scan R:R threshold (default 1.5:1 — distinct from the activation floor below)
|
||||
- Activation gate — qualifies setups on a residual-momentum percentile floor (the actual selection), a headline gate-target R:R floor (prod: 2.0) and a 20% primary-target reach-probability floor (validated long-only edge)
|
||||
- Recommendation layer — directional confidence, conflict detection, per-target reach-probability
|
||||
- Paper trading — take a setup, mark-to-market vs. latest close, auto-close per the exit policy (default: 3x ATR trail with a 30-trading-day max hold; time / percent-trailing / target-stop selectable), realized track record + outcome evaluation
|
||||
- Market-regime index + FRED early-warning monitor (VIX, credit spreads); weekly backtest + manual event study
|
||||
- Shadow book — opt-in automated twin of the backtest's selection rule (top-ranked qualified setups up to capacity, every near-close scan), sharing the manual book's exit policy; the honest forward out-of-sample record
|
||||
- System events — structured job/import/data warnings with acknowledgement, surfaced in Admin and deduplicated for alerting
|
||||
- Market-regime guard + observational State/Warning monitor (fixed-basket breadth, VIX, credit level + impulse) with a manual chronological correction study
|
||||
- Telegram alerts (e.g. regime-quadrant changes)
|
||||
- User-curated watchlist (cap: 20), enriched with composite score, R:R and S/R summary
|
||||
- JWT auth with admin role, configurable registration, user access control
|
||||
@@ -165,12 +396,17 @@ Corollaries: never let an unvalidated score gate setups; the outcome evaluator m
|
||||
- Glassmorphism UI with frosted glass panels, gradient text, ambient glow effects, mesh gradient background
|
||||
- Interactive candlestick chart (Canvas 2D) with hover tooltips showing OHLCV values
|
||||
- Support/Resistance level overlays on chart (top 6 by strength, dashed lines with labels)
|
||||
- Optional GTL price-traffic profile on the ticker chart (right-edge diagnostic; explicitly not volume)
|
||||
- Production-rank strip below the ticker chart (80/20 contribution ledger plus separate momentum and volatility percentiles)
|
||||
- Data freshness bar showing availability and recency of each data source
|
||||
- Watchlist with composite scores, R:R ratios, and S/R summaries
|
||||
- Ticker detail page: chart, scores, sentiment breakdown, fundamentals, technical indicators, S/R table
|
||||
- Rankings table with configurable dimension weights
|
||||
- Trade scanner showing detected R:R setups
|
||||
- Admin page: user management, job status with live indicators, enable/disable toggles, data cleanup, system settings
|
||||
- Backtest tab: portfolio monitor vs SPY over selectable lookbacks, headline risk-adjusted tiles (Sharpe, Sortino, Gain-to-Pain, dollar profit factor), the report's recommendation card, and a live-outcome evaluation panel
|
||||
- Dashboard performance chart: cumulative shadow book vs discretionary book vs SPY since the configured start date
|
||||
- Paper Trades tab: open/closed discretionary trades with realized R and P&L tiles
|
||||
- Admin page: user management, job status with live indicators, enable/disable toggles, pipeline readiness, system-event log, ticker management, data cleanup, system settings
|
||||
- Protected routes with JWT auth, admin-only sections
|
||||
- Responsive layout with mobile navigation
|
||||
- Toast notifications for async operations
|
||||
@@ -181,14 +417,14 @@ Corollaries: never let an unvalidated score gate setups; the outcome evaluator m
|
||||
|---|---|---|
|
||||
| `/login` | Login | Public |
|
||||
| `/register` | Register | Public (when enabled) |
|
||||
| `/` | Dashboard — top setups, open trades, regime (default) | Authenticated |
|
||||
| `/` | Dashboard — top setups, open trades, regime, shadow-vs-manual-vs-SPY performance chart (default) | Authenticated |
|
||||
| `/market` | Market — watchlist + rankings tabs | Authenticated |
|
||||
| `/signals` | Signals — scanner + track record tabs | Authenticated |
|
||||
| `/regime` | Market Regime | Authenticated |
|
||||
| `/signals` | Signals — Setups / Paper Trades / Backtest tabs | Authenticated |
|
||||
| `/regime` | AI/Tech Risk Monitor | Authenticated |
|
||||
| `/ticker/:symbol` | Ticker Detail | Authenticated |
|
||||
| `/admin` | Admin Panel | Admin only |
|
||||
|
||||
Legacy routes redirect: `/watchlist` → `/market`, `/rankings` → `/market?tab=rankings`, `/scanner` → `/signals`, `/performance` → `/signals?tab=track`.
|
||||
Legacy routes redirect: `/watchlist` → `/market`, `/rankings` → `/market?tab=rankings`, `/scanner` → `/signals`, `/performance` → `/signals?tab=track` (the Paper Trades tab — `track` stays its slug so the old link keeps working).
|
||||
|
||||
## API Endpoints
|
||||
|
||||
@@ -198,20 +434,21 @@ All under `/api/v1/`. Interactive docs at `/docs` (Swagger) and `/redoc`.
|
||||
|---|---|
|
||||
| Health | `GET /health` |
|
||||
| Auth | `POST /auth/register`, `POST /auth/login` |
|
||||
| Tickers | `POST /tickers`, `GET /tickers`, `DELETE /tickers/{symbol}` |
|
||||
| Tickers | `POST /tickers`, `GET /tickers`, `DELETE /tickers/{symbol}`, `POST /tickers/{symbol}/delisting`, `DELETE /tickers/{symbol}/delisting` |
|
||||
| OHLCV | `POST /ohlcv`, `GET /ohlcv/{symbol}` |
|
||||
| Ingestion | `POST /ingestion/fetch/{symbol}` |
|
||||
| Indicators | `GET /indicators/{symbol}/{type}`, `GET /indicators/{symbol}/ema-cross` |
|
||||
| S/R Levels | `GET /sr-levels/{symbol}` |
|
||||
| Gate Target Ladder | `GET /gate-target-ladder/{symbol}` |
|
||||
| Sentiment | `GET /sentiment/{symbol}` |
|
||||
| Fundamentals | `GET /fundamentals/{symbol}` |
|
||||
| Scores | `GET /scores/{symbol}`, `GET /rankings`, `PUT /scores/weights` |
|
||||
| Trades | `GET /trades`, `GET /trades/{symbol}`, `GET /trades/{symbol}/history`, `GET /trades/activation`, `GET /trades/performance` |
|
||||
| Paper Trades | `GET /paper-trades`, `POST /paper-trades`, `POST /paper-trades/{id}/close` |
|
||||
| Market / Regime | `GET /market/regime`, `GET /regime/monitor`, `GET/PUT /regime/config`, `GET /regime/history`, `GET /regime/event-study`, `GET/PUT /regime/fundamentals`, `GET /backtest/report` |
|
||||
| Paper Trades | `GET /paper-trades`, `POST /paper-trades`, `POST /paper-trades/{id}/close`, `GET /paper-trades/equity-curve`, `GET /paper-trades/performance` (shadow vs manual vs SPY), `GET/PUT /paper-trades/exit-policy` |
|
||||
| Market / Regime | `GET /market/regime`, `GET /regime/monitor`, `GET/PUT /regime/config`, `GET /regime/history`, `GET /regime/event-study`, `GET/PUT /regime/fundamentals`, `POST /regime/fundamentals/refresh`, `GET /backtest/report` |
|
||||
| Jobs | `GET /jobs/running` |
|
||||
| Watchlist | `GET /watchlist`, `POST /watchlist/{symbol}`, `DELETE /watchlist/{symbol}` |
|
||||
| Admin | `GET /admin/users`, `POST /admin/users`, `PUT /admin/users/{id}/access`, `PUT /admin/users/{id}/password`, `PUT /admin/settings/registration`, `GET /admin/settings`, `PUT /admin/settings/{key}`, `GET/PUT /admin/settings/recommendations`, `GET/PUT /admin/settings/ticker-universe`, `POST /admin/tickers/bootstrap`, `POST /admin/data/cleanup`, `GET /admin/jobs`, `POST /admin/jobs/{name}/trigger`, `PUT /admin/jobs/{name}/toggle`, `GET /admin/pipeline/readiness` |
|
||||
| Admin | `GET /admin/users`, `POST /admin/users`, `PUT /admin/users/{id}/access`, `PUT /admin/users/{id}/password`, `PUT /admin/settings/registration`, `GET /admin/settings`, `PUT /admin/settings/{key}`, `GET/PUT /admin/settings/{recommendations,activation,schedule,performance,shadow-book,sentiment,alerts,ticker-universe}`, `POST /admin/settings/{sentiment,alerts}/test`, `POST /admin/tickers/bootstrap`, `POST /admin/tickers/backfill-names`, `POST /admin/data/cleanup`, `POST /admin/track-record/reset`, `GET /admin/jobs`, `POST /admin/jobs/{name}/trigger`, `PUT /admin/jobs/{name}/toggle`, `GET /admin/pipeline/readiness`, `GET /admin/system-events`, `GET /admin/system-events/summary`, `POST /admin/system-events/acknowledge` |
|
||||
|
||||
## Development Setup
|
||||
|
||||
@@ -271,8 +508,8 @@ npm run preview # Preview the production build locally
|
||||
# Backend tests (in-memory SQLite — no PostgreSQL needed)
|
||||
pytest tests/ -v
|
||||
|
||||
# Frontend: there is no test suite — `npm test` calls vitest, which is not
|
||||
# installed. The frontend check is the full TypeScript build:
|
||||
# Frontend: there is no test suite and no `test` script at all. The frontend
|
||||
# check is the full TypeScript build:
|
||||
cd frontend
|
||||
npm run build
|
||||
```
|
||||
@@ -282,7 +519,13 @@ npm run build
|
||||
For research loops, run the production backtest locally from a SQLite snapshot
|
||||
instead of deploying and clicking the Admin job. The snapshot contains only the
|
||||
tables needed by `run_backtest`: tickers, OHLCV bars, SPY benchmark closes, and
|
||||
activation/recommendation settings. Secrets and cached reports are not copied.
|
||||
the activation / recommendation / paper-exit settings. Secrets and cached reports
|
||||
are not copied.
|
||||
|
||||
> The `paper_%` settings **must** be copied: the portfolio monitor's Production row
|
||||
> replays the *runtime* exit policy via `get_exit_policy()`. Without them a snapshot
|
||||
> silently falls back to the code defaults, so a live-tuned exit would not be
|
||||
> reflected and the local run would disagree with prod for no visible reason.
|
||||
|
||||
1. Open an SSH tunnel to the production Postgres instance:
|
||||
|
||||
@@ -316,6 +559,14 @@ python scripts/run_backtest_snapshot.py backtest_snapshots/prod.sqlite --workers
|
||||
.venv\Scripts\python.exe scripts\run_backtest_snapshot.py backtest_snapshots\prod.sqlite --workers 6 --allow-spawn
|
||||
```
|
||||
|
||||
Weekly remains the resource-safe default. Add `--cadence daily` for live-like daily entry opportunities; this performs roughly five times as many setup evaluations. To generate the complete weekly/daily × immediate/gate-reset comparison in one invocation, use:
|
||||
|
||||
```bash
|
||||
python scripts/run_backtest_cadence_comparison.py backtest_snapshots/prod.sqlite --workers 7
|
||||
```
|
||||
|
||||
On Windows, add `--allow-spawn`. The comparison runner writes the two full cadence reports plus one compact four-arm report. For the larger nine-policy daily research matrix used in the post-stop decision, see `scripts/run_daily_reentry_matrix.py` and the [research record](docs/research/post-stop-reentry.md).
|
||||
|
||||
On an 8-thread machine, `--workers 6` is a good starting point: it leaves a
|
||||
couple of threads for Windows, the shell, and browser/UI work while still using
|
||||
most of the CPU.
|
||||
@@ -325,12 +576,27 @@ metrics. Keep the SSH tunnel open only while creating the snapshot; the backtest
|
||||
run itself is local/offline. `backtest_snapshots/` and generated backtest reports
|
||||
are git-ignored.
|
||||
|
||||
The local runner, scheduled job, and Admin UI all default to
|
||||
`production_gtl`, matching the live scanner's target path. For a deliberate
|
||||
comparison, select **Structural S/R (comparison)** in the UI or pass
|
||||
`--target-model structural_sr` locally. Every report records the selected model
|
||||
and whether it is the production path.
|
||||
|
||||
### Archived GTL tuning decision
|
||||
|
||||
The completed replacement, cohort-composition, and strength-sensitivity
|
||||
matrices found no stable improvement over the frozen Gate Target Ladder. The
|
||||
temporary matrix runners and tuning hooks have been retired; their three compact
|
||||
consolidated report pairs remain in `reports/` as the decision audit. Keep the
|
||||
GTL unchanged and evaluate any future challenger only on new forward data. See
|
||||
the [full research record](docs/research/sr-levels-and-exits.md#gtl-tuning-matrix).
|
||||
|
||||
### Reading a local backtest report
|
||||
|
||||
The deployed **Signals → Track Record** page is deliberately trimmed to validation
|
||||
(portfolio monitor vs SPY, realized paper trades) and how-to-trade. The
|
||||
strategy-tuning tables that used to live there now live **only** in the local
|
||||
report — inspect these `reports/backtest-<timestamp>.json` sections and produce the
|
||||
The deployed **Signals → Backtest** tab is deliberately trimmed to validation
|
||||
(portfolio monitor vs SPY, headline metrics, the report's recommendation, and the
|
||||
live-outcome evaluation panel). The strategy-tuning tables that used to live there
|
||||
now live **only** in the local report — inspect these `reports/backtest-<timestamp>.json` sections and produce the
|
||||
matching decision. Every change still goes through the factor harness first (see
|
||||
**The iron rule for strategy changes** above).
|
||||
|
||||
@@ -341,11 +607,37 @@ matching decision. Every change still goes through the factor harness first (see
|
||||
| `gate_ablation` | Net expectancy with each floor removed | Drop a floor only if removing it doesn't hurt net expectancy |
|
||||
| `time_exit_sweep` | Net avg R / net R-per-day by hold length | Whether a fixed time exit beats the promoted ATR trail |
|
||||
| `portfolio_monitor`, `portfolio_sim`, `strategy_variants` | CAGR, Sharpe, max drawdown, per-year returns | Promote a strategy only if it beats the current baseline on CAGR/Sharpe/DD |
|
||||
| `production_cadence_comparison` | Immediate vs production gate reset at the selected weekly or daily cadence | Isolates the re-entry rule while keeping gate, rank, exit, fees, sizing, and capacity fixed |
|
||||
| `signal_eval` | Mean IC, t-stat, IC>0 %, `reliable` | Iron rule: wire a new factor in only if \|IC\| ≳ 0.03 with a consistent sign and `reliable: true` |
|
||||
| `holdout` (opt-in) | Train vs test books, split by entry date | **The only honest OOS read.** Set `BACKTEST_HOLDOUT_SPLIT=YYYY-MM-DD` |
|
||||
| `recommendation`, `research_recommendation` | The report's own headline read | A starting point, not a substitute for the sections above |
|
||||
|
||||
`recommendation` is the one section surfaced on the deployed page ("What this
|
||||
backtest recommends"); everything else in this table is intentionally local-only.
|
||||
**Out-of-sample validation.** The `portfolio_monitor` lookbacks (6m / 1y / 3y / 5y / all) are
|
||||
**nested windows that all end today** — every one of them overlaps the data an idea was found
|
||||
on, so none of them is a holdout. A rule that looks good across all five can still be an
|
||||
in-sample artifact (this exact trap ate the clear-air experiment; see the research log). For a
|
||||
real train/test split by entry date:
|
||||
|
||||
```bash
|
||||
BACKTEST_HOLDOUT_SPLIT=2024-07-01 python scripts/run_backtest_snapshot.py \
|
||||
backtest_snapshots/prod.sqlite --workers 7 --allow-spawn
|
||||
```
|
||||
|
||||
Research-only flags, all off by default (the default report is byte-identical to the shipped baseline):
|
||||
|
||||
| Flag | What it does |
|
||||
|---|---|
|
||||
| `BACKTEST_HOLDOUT_SPLIT=YYYY-MM-DD` | Adds a `holdout` section: train (entries before) vs test (entries on/after), as disjoint books |
|
||||
| `BACKTEST_MIN_RR_SWEEP=1` | Sweeps the activation R:R floor against portfolio Sharpe. Combine with `BACKTEST_HOLDOUT_SPLIT` to sweep out-of-sample |
|
||||
| `BACKTEST_RESEARCH_EXITS=1` | Adds the rejected take-profit exit rows to the exit comparison |
|
||||
| `BACKTEST_ATR_TARGET_FALLBACK=k` | Synthesizes a k×ATR target where S/R offers none |
|
||||
| `BACKTEST_FALLBACK_CLEAR_AIR_ONLY=1` | Restricts that fallback to setups with genuinely no structure ahead |
|
||||
|
||||
`portfolio_monitor` and `recommendation` are the sections surfaced on the deployed
|
||||
Backtest tab (the monitor chart/tiles and "What this backtest recommends"; the
|
||||
recommendation is rebuilt on read, so it always matches the lookback on screen and
|
||||
flags one it was not computed on). Everything else in this table is intentionally
|
||||
local-only.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
@@ -363,20 +655,25 @@ Configure in `.env` (copy from `.env.example`):
|
||||
| `OPENAI_API_KEY` | For sentiment (OpenAI path) | — | OpenAI API key |
|
||||
| `OPENAI_MODEL` | No | `gpt-4o-mini` | OpenAI model name |
|
||||
| `OPENAI_SENTIMENT_BATCH_SIZE` | No | `5` | Micro-batch size for sentiment collector |
|
||||
| `FMP_API_KEY` | Optional (fundamentals) | — | Financial Modeling Prep API key (first provider in chain) |
|
||||
| `FINNHUB_API_KEY` | Optional (fundamentals) | — | Finnhub API key (fallback provider) |
|
||||
| `ALPHA_VANTAGE_API_KEY` | Optional (fundamentals) | — | Alpha Vantage API key (fallback provider) |
|
||||
| `FRED_API_KEY` | Optional (regime) | — | FRED key for the regime monitor (VIX, credit spreads) |
|
||||
| `DEEPSEEK_API_KEY` / `XAI_API_KEY` | For sentiment (those paths) | — | Alternative pluggable sentiment providers |
|
||||
| `SEC_USER_AGENT` | **For fundamentals** | placeholder | SEC EDGAR requires a real `name (contact: email)` UA — the shipped default is a placeholder and SEC will throttle/refuse it |
|
||||
| `SEC_REQUEST_SPACING_SECONDS` | No | `0.2` | Politeness delay between SEC requests |
|
||||
| `SEC_MAX_RETRIES` / `SEC_REQUEST_TIMEOUT_SECONDS` | No | `4` / `30` | SEC client retry and timeout budget |
|
||||
| `DOLT_BINARY` | For earnings import | `dolt` | Path to the `dolt` executable |
|
||||
| `DOLT_DATA_DIR` / `DOLT_EARNINGS_SUBDIR` | No | `dolt-data` / `earnings` | Local Dolt clone location |
|
||||
| `DOLT_MIN_FREE_DISK_GB` | No | `5.0` | Refuse to clone/pull below this free space |
|
||||
| `DOLT_COMMAND_TIMEOUT_SECONDS` | No | `600` | Per-command Dolt timeout |
|
||||
| `FRED_API_KEY` | Optional (risk monitor) | — | FRED key for the AI/Tech risk monitor (VIX, credit spreads) |
|
||||
| `TELEGRAM_BOT_TOKEN` | Optional (alerts) | — | Telegram bot token for alerts (can also be set in Admin) |
|
||||
| `TELEGRAM_CHAT_ID` | Optional (alerts) | — | Telegram chat id for alerts |
|
||||
| `DATA_COLLECTOR_FREQUENCY` | No | `daily` | OHLCV collection schedule (legacy — see note below) |
|
||||
| `SENTIMENT_POLL_INTERVAL_MINUTES` | No | `30` | Sentiment polling interval |
|
||||
| `FUNDAMENTAL_FETCH_FREQUENCY` | No | `weekly` | Fundamentals fetch cadence |
|
||||
| `RR_SCAN_FREQUENCY` | No | `daily` | R:R scanner schedule |
|
||||
| `FUNDAMENTAL_RATE_LIMIT_RETRIES` | No | `3` | Retries per ticker on fundamentals rate-limit |
|
||||
| `FUNDAMENTAL_RATE_LIMIT_BACKOFF_SECONDS` | No | `15` | Base backoff seconds for fundamentals retry (exponential) |
|
||||
| `DEFAULT_WATCHLIST_AUTO_SIZE` | No | `10` | Auto-watchlist size |
|
||||
| `DEFAULT_RR_THRESHOLD` | No | `1.5` | Minimum R:R ratio for setups |
|
||||
| `OHLCV_HISTORY_DAYS` | No | `1825` | Backfill depth for new tickers (~5 years) |
|
||||
| `OUTCOME_EVALUATION_MAX_BARS` | No | `30` | Bars the outcome evaluator resolves a setup over |
|
||||
| `BACKTEST_WORKERS` | No | `4` | Worker processes for the scheduled backtest |
|
||||
| `DB_POOL_SIZE` | No | `5` | Database connection pool size |
|
||||
| `LOG_LEVEL` | No | `INFO` | Logging level |
|
||||
|
||||
@@ -469,7 +766,9 @@ app/
|
||||
├── exceptions.py # Exception hierarchy
|
||||
├── middleware.py # Global error handler → JSON envelope
|
||||
├── cache.py # LRU cache with per-ticker invalidation
|
||||
├── ssl_bootstrap.py # TLS trust-store bootstrap for outbound calls
|
||||
├── scheduler.py # APScheduler job definitions
|
||||
├── job_catalog.py # Single source of truth for job names + pipeline step lists
|
||||
├── models/ # SQLAlchemy ORM models
|
||||
├── schemas/ # Pydantic request/response schemas
|
||||
├── services/ # Business logic layer
|
||||
@@ -489,9 +788,11 @@ frontend/
|
||||
│ ├── admin/ # User table, job controls, settings, data cleanup
|
||||
│ ├── auth/ # Protected route wrapper
|
||||
│ ├── charts/ # Canvas candlestick chart
|
||||
│ ├── dashboard/ # Top setups, open trades, shadow-vs-manual performance chart
|
||||
│ ├── layout/ # App shell, sidebar, mobile nav
|
||||
│ ├── rankings/ # Rankings table, weights form
|
||||
│ ├── scanner/ # Trade table
|
||||
│ ├── signals/ # Setups / Paper Trades / Backtest panels
|
||||
│ ├── ticker/ # Sentiment panel, fundamentals, indicators, S/R overlay
|
||||
│ ├── ui/ # Badge, toast, skeleton, score card, confirm dialog
|
||||
│ └── watchlist/ # Watchlist table, add ticker form
|
||||
@@ -501,10 +802,27 @@ frontend/
|
||||
├── stores/ # Zustand auth store
|
||||
└── styles/ # Global CSS with glassmorphism classes
|
||||
|
||||
docs/
|
||||
├── dolt-integration-plan.md # Design record for the Dolt/SEC fundamentals workstream
|
||||
├── dolt-sec-a3-design.md
|
||||
├── fundamentals-deployment.md
|
||||
└── research/ # Experiment log: what was tested, the result, the decision
|
||||
├── README.md # Overview — start here before proposing a strategy change
|
||||
├── sr-levels-and-exits.md
|
||||
├── post-stop-reentry.md
|
||||
├── portfolio-capacity-bracket*.md
|
||||
├── execution-recovery.md
|
||||
├── fip-breadth-ic.md
|
||||
├── regime-monitor-v3.md / -v4.md
|
||||
└── … # 16 documents total
|
||||
|
||||
reports/ # Committed backtest reports (JSON) + compare_reports.py
|
||||
|
||||
deploy/
|
||||
├── nginx.conf # Reverse proxy + static file serving
|
||||
├── setup_db.sh # Idempotent DB setup script
|
||||
└── stock-data-backend.service # systemd unit
|
||||
├── provision_fundamentals.sh # Server-side Dolt/SEC fundamentals provisioning
|
||||
└── signalplatform.service # systemd unit
|
||||
|
||||
tests/
|
||||
├── conftest.py # Fixtures, strategies, test DB
|
||||
@@ -519,11 +837,14 @@ Context for whoever — human or AI — continues this work. The owner pushes st
|
||||
### Invariants — do not break these
|
||||
|
||||
- **`app/services/qualification.py` is mirrored in `frontend/src/lib/qualification.ts`.** Any gate change must land in both, or the UI's "qualified" flags silently disagree with the server.
|
||||
- **Live scan and backtest share the same pure functions.** The backtest replays production logic through DB-free functions (`compute_technical_from_arrays`, `compute_momentum_from_closes`, `detect_sr_levels`, the recommendation helpers). New strategy logic must stay in pure functions consumed by both paths, or the backtest stops measuring what production actually does.
|
||||
- **One S/R model app-wide:** `sr_service.detect_sr_levels` + `cluster_sr_zones` (2% tolerance) feed the chart, alerts, and target generation identically.
|
||||
- **The outcome evaluator evaluates ALL setups**, not just qualified ones — unqualified setups are the control group that makes the Track Record meaningful.
|
||||
- **Live scan and backtest share the same pure functions.** The backtest replays production logic through DB-free functions (`compute_technical_from_arrays`, `compute_momentum_from_closes`, `detect_sr_levels`, `detect_gate_target_ladder`, the recommendation helpers). New strategy logic must stay in pure functions consumed by both paths, or the backtest stops measuring what production actually does.
|
||||
- **Keep the two price-level models separate.** `detect_sr_levels` produces persisted Structural S/R for charts and alerts. `detect_gate_target_ladder` produces transient screening proposals and must never be persisted or presented as market structure. The scanner must not read `SRLevel` rows for target generation.
|
||||
- **The Gate Target Ladder target is a gate input, never an exit.** `_atr_trailing_close()` does not take it as a parameter, and it must stay that way — take-profit exits were tested and halve CAGR. Any UI or alert that implies the trade exits at the target is a bug ([research](docs/research/sr-levels-and-exits.md#explicit-gate-target-ladder)).
|
||||
- **The outcome evaluator evaluates ALL setups**, not just qualified ones — unqualified setups are the control group that makes the realized-outcome record meaningful.
|
||||
- **`SystemSetting` access goes through `app/services/settings_store.py`** — don't query the model directly.
|
||||
- **Time-series data gets a real table** (see `benchmark_prices`, `regime_snapshots`); `SystemSetting` JSON is only for config and cached reports.
|
||||
- **The shadow book must stay parity-clean.** It orders on the *stored* `strategy_rank` the scanner wrote and mirrors `_simulate_portfolio`'s selection rule; it accepts only a scan from its own pipeline run. Recomputing its ranking, or letting it consume a stale/manual scan, turns the forward OOS record back into an approximation.
|
||||
- **Delisted tickers are retired, never deleted.** Live paths opt into `ticker_service.active_only`; the registry, admin views and `run_backtest` deliberately still see them. Deleting a symbol takes the history that a survivorship-bias fix would need.
|
||||
- **Discretionary overlay data is forward-only.** `signal_context_snapshots` captures composite/dimension/sentiment/fundamental context for new setups. Do not approximate historical sentiment/fundamental snapshots from today's data.
|
||||
- Style: surgical changes, minimal new files; extend existing services rather than adding parallel ones.
|
||||
|
||||
@@ -533,17 +854,21 @@ Context for whoever — human or AI — continues this work. The owner pushes st
|
||||
|---|---|
|
||||
| Composite + 5 dimension scores, weights | `app/services/scoring_service.py` |
|
||||
| Residual 12-1 momentum ranking (the validated activation factor) | `app/services/momentum_service.py` |
|
||||
| Setup construction (ATR stop, S/R targets) | `app/services/rr_scanner_service.py` |
|
||||
| Setup construction (ATR stop, Gate Target Ladder targets) | `app/services/rr_scanner_service.py` |
|
||||
| Confidence, targets, reach-probability, action | `app/services/recommendation_service.py` |
|
||||
| Activation gate predicate (mirrored in TS) | `app/services/qualification.py` |
|
||||
| Gate defaults / admin config | `app/services/admin_service.py` (`ACTIVATION_DEFAULTS`) |
|
||||
| Backtest + factor rank-IC harness ("Signal edge") | `app/services/backtest_service.py` |
|
||||
| Outcome resolution (target/stop/expired/ambiguous) | `app/services/outcome_service.py` |
|
||||
| Paper trades + time/trailing/target auto-exit | `app/services/paper_trade_service.py` |
|
||||
| Shadow book (automated twin of the backtest's selection) | `app/services/shadow_book_service.py` |
|
||||
| Re-entry locks / distinct-day guard / book identities | `app/services/trade_policy.py` |
|
||||
| Ticker registry, delisting + `active_only` filter | `app/services/ticker_service.py` |
|
||||
| Point-in-time setup context snapshots | `app/models/signal_context_snapshot.py` + `app/services/rr_scanner_service.py` |
|
||||
| S/R detection & zone clustering | `app/services/sr_service.py` |
|
||||
| Structural S/R detection, Gate Target Ladder & zone clustering | `app/services/sr_service.py` |
|
||||
| **Research log — what's been tested and rejected** | **`docs/research/`** |
|
||||
| SPY benchmark for residual momentum + paper-trade alpha | `app/services/benchmark_service.py` |
|
||||
| Pipelines & job registration | `app/scheduler.py` |
|
||||
| Pipelines & job registration | `app/scheduler.py` (step lists and job names in `app/job_catalog.py`) |
|
||||
|
||||
### Verifying changes
|
||||
|
||||
@@ -552,7 +877,7 @@ pytest tests/ -q # backend; in-memory SQLite, no Postgres needed
|
||||
cd frontend && npm run build # full tsc check — this IS the frontend "test"
|
||||
```
|
||||
|
||||
- `npm test` in `frontend/` is dead (vitest isn't installed; there are no frontend test files). Use `npm run build`.
|
||||
- There is no `npm test` in `frontend/` — no test script, no test files. `npm run build` (`tsc -b && vite build`) is the frontend check.
|
||||
- Backend tests that exercise services which `commit()` need a plain session fixture, not the rolling-back `db_session` — copy the pattern in `tests/unit/test_rr_scanner_integration.py`.
|
||||
- `ruff` reports ~11 pre-existing errors in old test files; those are not regressions.
|
||||
|
||||
@@ -569,6 +894,6 @@ Practical consequences:
|
||||
|
||||
### Roadmap (agreed June 2026)
|
||||
|
||||
1. **Forward paper-test the momentum book** — the out-of-sample proof the backtest can't give. Watch Signals → Track Record (live vs backtest).
|
||||
1. **Forward paper-test the momentum book** — the out-of-sample proof the backtest can't give. Watch the Dashboard chart (shadow book vs discretionary vs SPY) against Signals → Backtest.
|
||||
2. **Full IBKR integration** — read real positions, overlay entries/stops on charts, alert on holdings' score deterioration. (Paper trading, the lighter alternative, is done.)
|
||||
3. Strategy experiments in the order listed under **Strategy Status** above — each one goes through the factor harness first.
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Drop the orphaned EV-gate activation settings.
|
||||
|
||||
``activation_min_expected_value`` and ``activation_min_target_probability`` are
|
||||
leftovers from the June 2026 EV-gate redesign (migration 009). That gate was
|
||||
superseded by the residual-momentum gate, and the current code reads neither key:
|
||||
``admin_service._ACTIVATION_FLOAT_KEYS`` exposes only ``min_momentum_percentile``,
|
||||
``min_rr`` and ``min_confidence``, and ``qualification.setup_qualifies`` gates on
|
||||
those plus the hardcoded ``MIN_TARGET_PROBABILITY`` floor.
|
||||
|
||||
The rows are therefore inert but actively misleading: prod carries
|
||||
``activation_min_target_probability = 50.0``, so anyone reading the DB (or an
|
||||
Admin screen rendering it) would reasonably believe a 50% probability floor is
|
||||
enforced. It is not — the real floor is the 20% constant in ``qualification.py``.
|
||||
|
||||
Reads never recreate them (``settings_store.get_value`` returns a default without
|
||||
persisting), and the current Admin write path no longer emits these keys, so the
|
||||
delete is permanent. Follows the precedent of migrations 009, 015 and 018.
|
||||
|
||||
Revision ID: 020
|
||||
Revises: 019
|
||||
Create Date: 2026-07-12 00:00:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "020"
|
||||
down_revision = "019"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
ORPHANED_KEYS = (
|
||||
"activation_min_expected_value",
|
||||
"activation_min_target_probability",
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute(
|
||||
sa.text(
|
||||
"DELETE FROM system_settings WHERE key IN "
|
||||
"('activation_min_expected_value', 'activation_min_target_probability')"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Restore the values prod carried before the delete. They are inert either
|
||||
# way — no code path reads them — but this keeps the downgrade faithful.
|
||||
# ``updated_at`` is NOT NULL with only a Python-side default, so raw SQL must
|
||||
# supply it explicitly.
|
||||
op.execute(
|
||||
sa.text(
|
||||
"INSERT INTO system_settings (key, value, updated_at) VALUES "
|
||||
"('activation_min_expected_value', '0.01', CURRENT_TIMESTAMP), "
|
||||
"('activation_min_target_probability', '50.0', CURRENT_TIMESTAMP) "
|
||||
"ON CONFLICT (key) DO NOTHING"
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,55 @@
|
||||
"""add system_events table for operational warnings/errors
|
||||
|
||||
Revision ID: 021
|
||||
Revises: 020
|
||||
Create Date: 2026-07-14 00:00:00.000000
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "021"
|
||||
down_revision: Union[str, None] = "020"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"system_events",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("severity", sa.String(length=16), nullable=False),
|
||||
sa.Column("source", sa.String(length=64), nullable=False),
|
||||
sa.Column("code", sa.String(length=64), nullable=False),
|
||||
sa.Column("message", sa.Text(), nullable=False),
|
||||
sa.Column("symbol", sa.String(length=20), nullable=True),
|
||||
sa.Column("dedup_key", sa.String(length=200), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("acknowledged_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_system_events_created_at",
|
||||
"system_events",
|
||||
["created_at"],
|
||||
)
|
||||
op.create_index(
|
||||
"ix_system_events_ack_created",
|
||||
"system_events",
|
||||
["acknowledged_at", "created_at"],
|
||||
)
|
||||
op.create_index(
|
||||
"ix_system_events_dedup_created",
|
||||
"system_events",
|
||||
["dedup_key", "created_at"],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_system_events_dedup_created", table_name="system_events")
|
||||
op.drop_index("ix_system_events_ack_created", table_name="system_events")
|
||||
op.drop_index("ix_system_events_created_at", table_name="system_events")
|
||||
op.drop_table("system_events")
|
||||
@@ -0,0 +1,53 @@
|
||||
"""add persistent post-stop gate-reset observation
|
||||
|
||||
Revision ID: 022
|
||||
Revises: 021
|
||||
Create Date: 2026-07-17 00:00:00.000000
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "022"
|
||||
down_revision: Union[str, None] = "021"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
"paper_trades",
|
||||
sa.Column("reentry_gate_failed_at", sa.DateTime(timezone=True), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"paper_trades",
|
||||
sa.Column(
|
||||
"reentry_gate_requalified_at",
|
||||
sa.DateTime(timezone=True),
|
||||
nullable=True,
|
||||
),
|
||||
)
|
||||
# The policy starts at this deployment. Historical NULL values mean the
|
||||
# scanner never recorded reset observations, not that those old episodes
|
||||
# are still active. Mark both transitions complete so only stops created
|
||||
# after the migration can open a re-entry lock.
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE paper_trades
|
||||
SET reentry_gate_failed_at = closed_at,
|
||||
reentry_gate_requalified_at = closed_at
|
||||
WHERE status = 'closed'
|
||||
AND close_reason = 'stop'
|
||||
AND closed_at IS NOT NULL
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("paper_trades", "reentry_gate_requalified_at")
|
||||
op.drop_column("paper_trades", "reentry_gate_failed_at")
|
||||
@@ -0,0 +1,73 @@
|
||||
"""near-close schedule cutover + paper trade fill_mode era tag
|
||||
|
||||
Revision ID: 023
|
||||
Revises: 022
|
||||
Create Date: 2026-07-18 00:00:00.000000
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "023"
|
||||
down_revision: Union[str, None] = "022"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
# Deliberate schedule rewrite (not a soft defaults refresh). Old stored values
|
||||
# are logged then replaced so prod does not keep scanning at 07:00 Berlin.
|
||||
_SCHEDULE_REWRITE: dict[str, str] = {
|
||||
"schedule_timezone": "America/New_York",
|
||||
"schedule_daily_pipeline_cron": "0 2 * * *",
|
||||
"schedule_near_close_pipeline_cron": "30 15 * * 1-5",
|
||||
"schedule_after_close_pipeline_cron": "45 16 * * 1-5",
|
||||
"schedule_intraday_pipeline_cron": "0 10-15 * * 1-5",
|
||||
"schedule_fundamentals_cron": "0 1 * * 1",
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
"paper_trades",
|
||||
sa.Column("fill_mode", sa.String(length=20), nullable=True),
|
||||
)
|
||||
|
||||
conn = op.get_bind()
|
||||
settings = sa.table(
|
||||
"system_settings",
|
||||
sa.column("id", sa.Integer),
|
||||
sa.column("key", sa.String),
|
||||
sa.column("value", sa.Text),
|
||||
sa.column("updated_at", sa.DateTime(timezone=True)),
|
||||
)
|
||||
now = sa.func.now()
|
||||
|
||||
for key, new_value in _SCHEDULE_REWRITE.items():
|
||||
row = conn.execute(
|
||||
sa.select(settings.c.value).where(settings.c.key == key)
|
||||
).fetchone()
|
||||
old_value = row[0] if row is not None else None
|
||||
# Always log so ops can recover the pre-cutover schedule from migration output.
|
||||
print(
|
||||
f"schedule_cutover {key}: {old_value!r} -> {new_value!r}",
|
||||
flush=True,
|
||||
)
|
||||
if row is None:
|
||||
conn.execute(
|
||||
sa.insert(settings).values(
|
||||
key=key, value=new_value, updated_at=now
|
||||
)
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
sa.update(settings)
|
||||
.where(settings.c.key == key)
|
||||
.values(value=new_value, updated_at=now)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("paper_trades", "fill_mode")
|
||||
# Do not restore old crons — unknown prior values; leave stored schedule as-is.
|
||||
@@ -0,0 +1,59 @@
|
||||
"""paper trade book tag (manual vs shadow) + weekday cron repair
|
||||
|
||||
Revision ID: 024
|
||||
Revises: 023
|
||||
Create Date: 2026-07-20 00:00:00.000000
|
||||
|
||||
Two things ship together because both are corrections to 023's stored state.
|
||||
|
||||
1. ``paper_trades.book`` separates the discretionary book from the automatic
|
||||
shadow book. Everything that exists today was opened by hand, so the
|
||||
backfill value is "manual".
|
||||
|
||||
2. 023 wrote weekday crons with a numeric day-of-week. APScheduler's
|
||||
from_crontab() feeds field 5 to its own day_of_week where 0=Monday, so
|
||||
"1-5" resolved to Tue-Sat: every Monday was skipped and the scanner ran on
|
||||
Saturdays against stale data. Rewrite only the rows that still hold the
|
||||
broken numeric form, so a hand-corrected setting is never clobbered.
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "024"
|
||||
down_revision: Union[str, None] = "023"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
# key -> (broken numeric form written by 023, corrected named form)
|
||||
_CRON_REPAIR: dict[str, tuple[str, str]] = {
|
||||
"schedule_near_close_pipeline_cron": ("30 15 * * 1-5", "30 15 * * mon-fri"),
|
||||
"schedule_after_close_pipeline_cron": ("45 16 * * 1-5", "45 16 * * mon-fri"),
|
||||
"schedule_intraday_pipeline_cron": ("0 10-15 * * 1-5", "0 10-15 * * mon-fri"),
|
||||
"schedule_fundamentals_cron": ("0 1 * * 1", "0 1 * * mon"),
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# server_default backfills existing rows, so no separate UPDATE is needed.
|
||||
op.add_column(
|
||||
"paper_trades",
|
||||
sa.Column("book", sa.String(length=10), nullable=False, server_default="manual"),
|
||||
)
|
||||
|
||||
# Literals are inlined rather than bound because bound parameters render as
|
||||
# NULL under `alembic upgrade --sql`, which would silently produce a script
|
||||
# that matches nothing. Every value here is a constant defined above.
|
||||
for key, (broken, fixed) in _CRON_REPAIR.items():
|
||||
op.execute(
|
||||
f"UPDATE system_settings SET value = '{fixed}' " # noqa: S608
|
||||
f"WHERE key = '{key}' AND value = '{broken}'"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("paper_trades", "book")
|
||||
# Crons are deliberately left corrected — restoring the numeric form would
|
||||
# reintroduce the skipped-Monday bug.
|
||||
@@ -0,0 +1,38 @@
|
||||
"""trade_setup scan_run_id — identity of the producing scan run
|
||||
|
||||
Revision ID: 025
|
||||
Revises: 024
|
||||
Create Date: 2026-07-21 00:00:00.000000
|
||||
|
||||
The shadow book must select the exact batch produced by its pipeline's scan.
|
||||
Matching the scan-completion marker's run id proves which scan wrote last, but
|
||||
setup selection was still a detected_at window that a concurrent manual scan
|
||||
could write rows into. Stamping each row with its scan's run id lets the shadow
|
||||
book select by identity instead. Existing rows are null (they predate the
|
||||
column and are never traded by the shadow book).
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "025"
|
||||
down_revision: Union[str, None] = "024"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
"trade_setups",
|
||||
sa.Column("scan_run_id", sa.String(length=32), nullable=True),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_trade_setups_scan_run_id", "trade_setups", ["scan_run_id"]
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_trade_setups_scan_run_id", table_name="trade_setups")
|
||||
op.drop_column("trade_setups", "scan_run_id")
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Dolt/SEC fundamentals schema — workstream A
|
||||
|
||||
Revision ID: 026
|
||||
Revises: 025
|
||||
Create Date: 2026-07-21 00:00:00.000000
|
||||
|
||||
Foundational schema for the Dolt bulk-data integration (workstream A): the
|
||||
batch import-run audit table, the SEC-sourced immutable fundamental snapshots
|
||||
(CIK-keyed, one row per accession), the Dolt earnings calendar/history, and the
|
||||
SEC issuer identity columns on ``tickers``. No data is populated here — the
|
||||
importers land in a later phase. ``fundamental_data`` is left untouched; its
|
||||
cutover is gated separately (phase A5). ``data_import_runs`` is created first
|
||||
because the other two tables carry an ``import_run_id`` FK to it.
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "026"
|
||||
down_revision: Union[str, None] = "025"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"data_import_runs",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("source", sa.String(length=32), nullable=False),
|
||||
sa.Column("revision", sa.String(length=64), nullable=True),
|
||||
sa.Column("status", sa.String(length=16), nullable=False),
|
||||
sa.Column("source_max_date", sa.Date(), nullable=True),
|
||||
sa.Column("row_counts_json", sa.Text(), nullable=True),
|
||||
sa.Column("validation_json", sa.Text(), nullable=True),
|
||||
sa.Column("started_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("completed_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("error_details", sa.Text(), nullable=True),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_data_import_runs_source_started", "data_import_runs", ["source", "started_at"]
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
"fundamental_snapshots",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("cik", sa.String(length=10), nullable=False),
|
||||
sa.Column("accession", sa.String(length=25), nullable=False),
|
||||
sa.Column("form", sa.String(length=12), nullable=False),
|
||||
sa.Column("filed_date", sa.Date(), nullable=False),
|
||||
sa.Column("accepted_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("period_start", sa.Date(), nullable=True),
|
||||
sa.Column("period_end", sa.Date(), nullable=False),
|
||||
sa.Column("fiscal_year", sa.Integer(), nullable=False),
|
||||
sa.Column("fiscal_period", sa.String(length=4), nullable=False),
|
||||
# duration facts — cumulative YTD/FY
|
||||
sa.Column("revenue", sa.Float(), nullable=True),
|
||||
sa.Column("net_income", sa.Float(), nullable=True),
|
||||
sa.Column("operating_income", sa.Float(), nullable=True),
|
||||
sa.Column("diluted_eps", sa.Float(), nullable=True),
|
||||
sa.Column("cfo", sa.Float(), nullable=True),
|
||||
sa.Column("capex", sa.Float(), nullable=True),
|
||||
sa.Column("depreciation_amortization", sa.Float(), nullable=True),
|
||||
# balance-sheet facts — period-end
|
||||
sa.Column("cash_and_st_investments", sa.Float(), nullable=True),
|
||||
sa.Column("total_debt", sa.Float(), nullable=True),
|
||||
sa.Column("shares_outstanding", sa.Float(), nullable=True),
|
||||
sa.Column("shares_outstanding_date", sa.Date(), nullable=True),
|
||||
sa.Column(
|
||||
"import_run_id",
|
||||
sa.Integer(),
|
||||
sa.ForeignKey("data_import_runs.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.UniqueConstraint("accession", name="uq_fundamental_snapshots_accession"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_fundamental_snapshots_cik_period",
|
||||
"fundamental_snapshots",
|
||||
["cik", "fiscal_year", "fiscal_period"],
|
||||
)
|
||||
op.create_index(
|
||||
"ix_fundamental_snapshots_cik_period_end",
|
||||
"fundamental_snapshots",
|
||||
["cik", "period_end"],
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
"earnings_events",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column(
|
||||
"ticker_id",
|
||||
sa.Integer(),
|
||||
sa.ForeignKey("tickers.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("announce_date", sa.Date(), nullable=False),
|
||||
sa.Column("session", sa.String(length=10), nullable=False),
|
||||
sa.Column("period_end", sa.Date(), nullable=True),
|
||||
sa.Column("eps_estimate", sa.Float(), nullable=True),
|
||||
sa.Column("eps_actual", sa.Float(), nullable=True),
|
||||
sa.Column("source", sa.String(length=32), nullable=False),
|
||||
sa.Column(
|
||||
"import_run_id",
|
||||
sa.Integer(),
|
||||
sa.ForeignKey("data_import_runs.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.UniqueConstraint("ticker_id", "announce_date", name="uq_earnings_ticker_announce"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_earnings_events_announce_date", "earnings_events", ["announce_date"]
|
||||
)
|
||||
|
||||
# SEC issuer identity on tickers (nullable; the only ticker<->issuer join point).
|
||||
op.add_column("tickers", sa.Column("cik", sa.String(length=10), nullable=True))
|
||||
op.add_column("tickers", sa.Column("sic", sa.String(length=4), nullable=True))
|
||||
op.add_column(
|
||||
"tickers", sa.Column("sic_description", sa.String(length=160), nullable=True)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("tickers", "sic_description")
|
||||
op.drop_column("tickers", "sic")
|
||||
op.drop_column("tickers", "cik")
|
||||
|
||||
op.drop_index("ix_earnings_events_announce_date", table_name="earnings_events")
|
||||
op.drop_table("earnings_events")
|
||||
|
||||
op.drop_index(
|
||||
"ix_fundamental_snapshots_cik_period_end", table_name="fundamental_snapshots"
|
||||
)
|
||||
op.drop_index(
|
||||
"ix_fundamental_snapshots_cik_period", table_name="fundamental_snapshots"
|
||||
)
|
||||
op.drop_table("fundamental_snapshots")
|
||||
|
||||
op.drop_index(
|
||||
"ix_data_import_runs_source_started", table_name="data_import_runs"
|
||||
)
|
||||
op.drop_table("data_import_runs")
|
||||
@@ -0,0 +1,43 @@
|
||||
"""fundamental_snapshots.weighted_avg_diluted_shares — market-cap fallback
|
||||
|
||||
Revision ID: 027
|
||||
Revises: 026
|
||||
Create Date: 2026-07-24 00:00:00.000000
|
||||
|
||||
Multi-class issuers report the cover-page share count per share class. That is a
|
||||
dimensional fact and Company Facts is non-dimensional, so it is absent entirely:
|
||||
META has never tagged it, CMCSA stops in 2009, BRK-B in 2011, CHTR in 2016 (when
|
||||
the Time Warner Cable deal made it multi-class). `shares_outstanding` is
|
||||
therefore null for a large slice of the mega-cap universe, which silently removes
|
||||
both `market_cap_est` and `fcf_yield`.
|
||||
|
||||
The weighted-average diluted count is always present (EPS requires it) and is
|
||||
consolidated across classes. Measured against issuers where the true
|
||||
point-in-time count IS available, it lands within ~0.6%: GOOGL 0.9936, MRNA
|
||||
1.0045, AAPL 0.9974, MSFT 0.9978.
|
||||
|
||||
Stored as its own column rather than backfilled into `shares_outstanding`, so the
|
||||
point-in-time column keeps its strict meaning and the fallback stays an explicit,
|
||||
labelled read-time decision. Existing rows are null until a reparse.
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "027"
|
||||
down_revision: Union[str, None] = "026"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
"fundamental_snapshots",
|
||||
sa.Column("weighted_avg_diluted_shares", sa.Float(), nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("fundamental_snapshots", "weighted_avg_diluted_shares")
|
||||
@@ -0,0 +1,147 @@
|
||||
"""SEC filing retry queue and setup-quality gate
|
||||
|
||||
Revision ID: 028
|
||||
Revises: 027
|
||||
Create Date: 2026-08-03 00:00:00.000000
|
||||
"""
|
||||
from datetime import date, datetime, timezone
|
||||
import json
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "028"
|
||||
down_revision: Union[str, None] = "027"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"sec_filing_gaps",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("cik", sa.String(length=10), nullable=False),
|
||||
sa.Column("accession", sa.String(length=25), nullable=False),
|
||||
sa.Column("form", sa.String(length=12), nullable=True),
|
||||
sa.Column("index_date", sa.Date(), nullable=True),
|
||||
sa.Column("reason", sa.String(length=64), nullable=False),
|
||||
sa.Column("coregistrant_ciks_json", sa.Text(), nullable=True),
|
||||
sa.Column("first_seen_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("last_attempted_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("escalated_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.UniqueConstraint("accession", name="uq_sec_filing_gaps_accession"),
|
||||
)
|
||||
op.create_index("ix_sec_filing_gaps_cik", "sec_filing_gaps", ["cik"])
|
||||
_backfill_retry_queue()
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_sec_filing_gaps_cik", table_name="sec_filing_gaps")
|
||||
op.drop_table("sec_filing_gaps")
|
||||
|
||||
|
||||
def _as_date(value) -> date | None:
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return date.fromisoformat(value)
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _backfill_retry_queue() -> None:
|
||||
"""Materialize pre-queue promoted gaps once; runtime never scans history."""
|
||||
bind = op.get_bind()
|
||||
runs = sa.table(
|
||||
"data_import_runs",
|
||||
sa.column("source", sa.String()),
|
||||
sa.column("status", sa.String()),
|
||||
sa.column("validation_json", sa.Text()),
|
||||
sa.column("source_max_date", sa.Date()),
|
||||
sa.column("started_at", sa.DateTime(timezone=True)),
|
||||
)
|
||||
snapshots = sa.table(
|
||||
"fundamental_snapshots",
|
||||
sa.column("cik", sa.String()),
|
||||
sa.column("accession", sa.String()),
|
||||
sa.column("filed_date", sa.Date()),
|
||||
)
|
||||
gaps = sa.table(
|
||||
"sec_filing_gaps",
|
||||
sa.column("cik", sa.String()),
|
||||
sa.column("accession", sa.String()),
|
||||
sa.column("form", sa.String()),
|
||||
sa.column("index_date", sa.Date()),
|
||||
sa.column("reason", sa.String()),
|
||||
sa.column("coregistrant_ciks_json", sa.Text()),
|
||||
sa.column("first_seen_at", sa.DateTime(timezone=True)),
|
||||
sa.column("last_attempted_at", sa.DateTime(timezone=True)),
|
||||
sa.column("escalated_at", sa.DateTime(timezone=True)),
|
||||
)
|
||||
|
||||
snapshot_rows = bind.execute(
|
||||
sa.select(snapshots.c.cik, snapshots.c.accession, snapshots.c.filed_date)
|
||||
).all()
|
||||
resolved_accessions = {row.accession for row in snapshot_rows}
|
||||
latest_filed_by_cik: dict[str, date] = {}
|
||||
for row in snapshot_rows:
|
||||
if row.filed_date is not None:
|
||||
current = latest_filed_by_cik.get(row.cik)
|
||||
if current is None or row.filed_date > current:
|
||||
latest_filed_by_cik[row.cik] = row.filed_date
|
||||
|
||||
audit_rows = bind.execute(
|
||||
sa.select(
|
||||
runs.c.validation_json,
|
||||
runs.c.source_max_date,
|
||||
runs.c.started_at,
|
||||
).where(
|
||||
runs.c.source == "sec_facts",
|
||||
runs.c.status == "promoted",
|
||||
runs.c.validation_json.is_not(None),
|
||||
)
|
||||
).all()
|
||||
now = datetime.now(timezone.utc)
|
||||
candidates: dict[str, dict] = {}
|
||||
for audit in audit_rows:
|
||||
try:
|
||||
summary = json.loads(audit.validation_json)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not isinstance(summary, dict):
|
||||
continue
|
||||
for item in summary.get("missing_xbrl") or []:
|
||||
accession = item.get("accession")
|
||||
raw_cik = item.get("cik")
|
||||
if not accession or raw_cik is None or accession in resolved_accessions:
|
||||
continue
|
||||
cik = str(raw_cik).zfill(10)
|
||||
index_date = _as_date(item.get("index_date")) or _as_date(
|
||||
audit.source_max_date
|
||||
)
|
||||
later_filed = latest_filed_by_cik.get(cik)
|
||||
if index_date is not None and later_filed is not None and later_filed > index_date:
|
||||
continue
|
||||
first_seen = audit.started_at or now
|
||||
existing = candidates.get(accession)
|
||||
if existing is not None and existing["first_seen_at"] <= first_seen:
|
||||
continue
|
||||
candidates[accession] = {
|
||||
"cik": cik,
|
||||
"accession": accession,
|
||||
"form": item.get("form"),
|
||||
"index_date": index_date,
|
||||
"reason": item.get("reason") or "not_in_companyfacts",
|
||||
"coregistrant_ciks_json": json.dumps(item.get("coregistrants") or []),
|
||||
"first_seen_at": first_seen,
|
||||
"last_attempted_at": first_seen,
|
||||
"escalated_at": None,
|
||||
}
|
||||
if candidates:
|
||||
op.bulk_insert(gaps, list(candidates.values()))
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Retire the legacy fundamentals settings (A6)
|
||||
|
||||
Revision ID: 029
|
||||
Revises: 028
|
||||
Create Date: 2026-08-07 00:00:00.000000
|
||||
|
||||
A6 removed the FMP/Finnhub/Alpha Vantage providers, the weekly
|
||||
``fundamental_collector`` job and the A5 parity report. Five SystemSetting rows
|
||||
are left over. They are NOT all deleted, because the deploy runs migrations
|
||||
before restarting the service: for a short window — and for the whole of any
|
||||
rollback — pre-A6 code is still live, and it reads absent rows permissively
|
||||
(cutover absent -> disabled; ``job_<name>_enabled`` absent -> enabled). Deleting
|
||||
both would hand a rolled-back process a re-armed legacy collector writing over
|
||||
the SEC/Dolt cache.
|
||||
|
||||
So the two rows that carry behavior become tombstones pinned to the safe value,
|
||||
and only the inert ones are deleted. The tombstones are dropped in a later
|
||||
release once the rollback window has closed; ``SettingsForm`` hides them
|
||||
meanwhile.
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "029"
|
||||
down_revision: Union[str, None] = "028"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
# Behavior-bearing under pre-A6 code -> pin to the safe value, keep the row.
|
||||
_TOMBSTONES: dict[str, str] = {
|
||||
"fundamental_data_sec_dolt_cutover_enabled": "true",
|
||||
"job_fundamental_collector_enabled": "false",
|
||||
}
|
||||
|
||||
# Inert either way: an absent cron falls back to a default for a job that no
|
||||
# longer registers, and the parity report never wrote anything.
|
||||
_OBSOLETE: tuple[str, ...] = (
|
||||
"schedule_fundamentals_cron",
|
||||
"schedule_fundamentals_parity_cron",
|
||||
"job_fundamentals_parity_report_enabled",
|
||||
)
|
||||
|
||||
_settings = sa.table(
|
||||
"system_settings",
|
||||
sa.column("id", sa.Integer),
|
||||
sa.column("key", sa.String),
|
||||
sa.column("value", sa.Text),
|
||||
sa.column("updated_at", sa.DateTime(timezone=True)),
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
now = sa.func.now()
|
||||
|
||||
for key, pinned in _TOMBSTONES.items():
|
||||
row = conn.execute(
|
||||
sa.select(_settings.c.value).where(_settings.c.key == key)
|
||||
).fetchone()
|
||||
old_value = row[0] if row is not None else None
|
||||
print(f"a6_tombstone {key}: {old_value!r} -> {pinned!r}", flush=True)
|
||||
if row is None:
|
||||
conn.execute(
|
||||
sa.insert(_settings).values(key=key, value=pinned, updated_at=now)
|
||||
)
|
||||
elif old_value != pinned:
|
||||
conn.execute(
|
||||
sa.update(_settings)
|
||||
.where(_settings.c.key == key)
|
||||
.values(value=pinned, updated_at=now)
|
||||
)
|
||||
|
||||
# Print the value before deleting — a bare DELETE cannot be undone from the
|
||||
# migration output.
|
||||
for key in _OBSOLETE:
|
||||
row = conn.execute(
|
||||
sa.select(_settings.c.value).where(_settings.c.key == key)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
print(f"a6_delete {key}: absent", flush=True)
|
||||
continue
|
||||
print(f"a6_delete {key}: {row[0]!r}", flush=True)
|
||||
conn.execute(sa.delete(_settings).where(_settings.c.key == key))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""No-op.
|
||||
|
||||
The deleted rows configured jobs this revision's code no longer registers,
|
||||
and the tombstones already hold the values pre-A6 code needs. Recreating
|
||||
them would restore nothing useful; the printed values above cover recovery.
|
||||
"""
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Drop the A6 rollback tombstones
|
||||
|
||||
Revision ID: 030
|
||||
Revises: 029
|
||||
Create Date: 2026-08-07 00:00:00.000000
|
||||
|
||||
Migration ``029`` kept two SystemSetting rows alive as rollback tombstones,
|
||||
pinned to the values a pre-A6 process needed to behave safely. A6 is deployed
|
||||
and healthy, and the provider keys are gone from the production ``.env`` — which
|
||||
makes the legacy collector inert regardless of any settings row — so the
|
||||
tombstones have no remaining job.
|
||||
|
||||
Nothing in the current codebase reads either key.
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "030"
|
||||
down_revision: Union[str, None] = "029"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
# The safe values 029 pinned. Kept here so downgrade restores real protection
|
||||
# rather than leaving a rolled-back process reading absent rows permissively.
|
||||
_TOMBSTONES: dict[str, str] = {
|
||||
"fundamental_data_sec_dolt_cutover_enabled": "true",
|
||||
"job_fundamental_collector_enabled": "false",
|
||||
}
|
||||
|
||||
_settings = sa.table(
|
||||
"system_settings",
|
||||
sa.column("id", sa.Integer),
|
||||
sa.column("key", sa.String),
|
||||
sa.column("value", sa.Text),
|
||||
sa.column("updated_at", sa.DateTime(timezone=True)),
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
for key in _TOMBSTONES:
|
||||
row = conn.execute(
|
||||
sa.select(_settings.c.value).where(_settings.c.key == key)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
print(f"a6_tombstone_drop {key}: absent", flush=True)
|
||||
continue
|
||||
print(f"a6_tombstone_drop {key}: {row[0]!r}", flush=True)
|
||||
conn.execute(sa.delete(_settings).where(_settings.c.key == key))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Restore the tombstones at their safe values.
|
||||
|
||||
Unlike 029's no-op downgrade, this one is meaningful: going back past this
|
||||
revision implies going back toward code that still reads these keys.
|
||||
"""
|
||||
conn = op.get_bind()
|
||||
now = sa.func.now()
|
||||
for key, pinned in _TOMBSTONES.items():
|
||||
exists = conn.execute(
|
||||
sa.select(_settings.c.id).where(_settings.c.key == key)
|
||||
).fetchone()
|
||||
if exists is None:
|
||||
conn.execute(
|
||||
sa.insert(_settings).values(key=key, value=pinned, updated_at=now)
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Durable last-run state per scheduled job
|
||||
|
||||
Revision ID: 031
|
||||
Revises: 030
|
||||
Create Date: 2026-08-08 00:00:00.000000
|
||||
|
||||
Job run state lived only in an in-memory dict in ``app.scheduler``, so every
|
||||
process restart wiped it. Admin → Jobs could then only report "Active" with no
|
||||
indication of whether a job had ever run, or how it ended — which is exactly
|
||||
the information an operator opens that page for.
|
||||
|
||||
One row per job, upserted on ``job_name``. Not history: ``system_events``
|
||||
already grows unbounded with no retention job, and a second append-only
|
||||
operational table would repeat that debt.
|
||||
|
||||
The table starts empty; each job populates its row the next time it finishes.
|
||||
No backfill from ``system_events`` — that table only records warning/error
|
||||
outcomes and uses a different status vocabulary, so seeding from it would
|
||||
invent successful runs that never happened.
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "031"
|
||||
down_revision: Union[str, None] = "030"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"job_run_state",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("job_name", sa.String(length=64), nullable=False),
|
||||
sa.Column("status", sa.String(length=32), nullable=False),
|
||||
sa.Column("started_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("processed", sa.Integer(), nullable=True),
|
||||
sa.Column("total", sa.Integer(), nullable=True),
|
||||
sa.Column("message", sa.Text(), nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("job_name", name="uq_job_run_state_job_name"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("job_run_state")
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Record delisting on tickers instead of deleting them
|
||||
|
||||
Revision ID: 032
|
||||
Revises: 031
|
||||
Create Date: 2026-08-11 00:00:00.000000
|
||||
|
||||
Until now the only way to retire a symbol was ``delete_ticker`` (or
|
||||
``bootstrap_universe(prune_missing=True)``), both of which cascade through
|
||||
OHLCV, setups and scores. That destroys exactly the history four research
|
||||
documents already apologise for: today's tracked universe projected backward
|
||||
is survivorship-biased, and hard-deleting every delisted name is what causes
|
||||
it. Keeping the rows preserves the option to fix that later — it does not fix
|
||||
it by itself, which needs the replay to model a delisting as an exit event.
|
||||
|
||||
``delisted_on`` is the effective date (from SEC Form 25/25-NSE/15 where we can
|
||||
confirm it, else the day it was marked); ``delisted_reason`` is a short code
|
||||
for how we learned. NULL in both means actively traded — the live signal path
|
||||
filters on that, while list and admin views keep showing the row so the
|
||||
delisting is visible rather than silently absent.
|
||||
|
||||
Nullable and reversible by design: clearing ``delisted_on`` un-retires a
|
||||
symbol, which is what makes automatic marking safe where a delete would not be.
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "032"
|
||||
down_revision: Union[str, None] = "031"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("tickers", sa.Column("delisted_on", sa.Date(), nullable=True))
|
||||
op.add_column(
|
||||
"tickers", sa.Column("delisted_reason", sa.String(length=32), nullable=True)
|
||||
)
|
||||
# The live path filters "actively traded" on every universe scan; the index
|
||||
# keeps that predicate cheap as delisted rows accumulate.
|
||||
op.create_index("ix_tickers_delisted_on", "tickers", ["delisted_on"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_tickers_delisted_on", table_name="tickers")
|
||||
op.drop_column("tickers", "delisted_reason")
|
||||
op.drop_column("tickers", "delisted_on")
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Point-in-time history for the sourced fundamental observation
|
||||
|
||||
Revision ID: 033
|
||||
Revises: 032
|
||||
Create Date: 2026-08-12 00:00:00.000000
|
||||
|
||||
The hyperscaler capex / "good news, stock down" read lived in a single
|
||||
``SystemSetting`` slot, so each refresh overwrote the last and no history
|
||||
existed. The read is now a categorical channel reported alongside State and
|
||||
Warning (never a term in either), and a channel with no history cannot be
|
||||
replayed: a snapshot rebuild would record every historical session as if nothing
|
||||
had ever been observed, and the event study could not measure the channel at all.
|
||||
|
||||
Keyed on ``effective_date`` (the session the observation becomes usable on,
|
||||
normally the next weekday) rather than ``fetched_at``, because that is the gate
|
||||
that stops a rebuild stamping today's reading onto historical rows.
|
||||
|
||||
The table starts empty. ``update_regime_monitor`` records the currently stored
|
||||
observation on its next run, so a deployment does not lose the live reading —
|
||||
but genuine history does not exist and cannot be invented here. Backfilling it
|
||||
from the SEC capex line and earnings-date reactions is separate work; until then
|
||||
every historical session reads ``unknown``, which is the honest value rather than
|
||||
a guessed one.
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "033"
|
||||
down_revision: Union[str, None] = "032"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"regime_fundamental_observations",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("effective_date", sa.Date(), nullable=False),
|
||||
sa.Column("f1_score", sa.Float(), nullable=True),
|
||||
sa.Column("f3_score", sa.Float(), nullable=True),
|
||||
sa.Column("capex_json", sa.Text(), nullable=False),
|
||||
sa.Column("good_news_stock_down", sa.String(length=10), nullable=False),
|
||||
sa.Column("reasoning", sa.Text(), nullable=True),
|
||||
sa.Column("source", sa.String(length=30), nullable=False),
|
||||
sa.Column("fetched_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
# One unique index, not a unique constraint plus a plain index: the model
|
||||
# declares `unique=True, index=True`, which SQLAlchemy renders as exactly
|
||||
# this. The constraint-plus-index pairing worked but left a redundant second
|
||||
# index on the column and a permanent metadata diff for autogenerate to keep
|
||||
# trying to reconcile. Matches RegimeSnapshot.date, the sibling table.
|
||||
op.create_index(
|
||||
"ix_regime_fundamental_observations_effective_date",
|
||||
"regime_fundamental_observations",
|
||||
["effective_date"],
|
||||
unique=True,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index(
|
||||
"ix_regime_fundamental_observations_effective_date",
|
||||
table_name="regime_fundamental_observations",
|
||||
)
|
||||
op.drop_table("regime_fundamental_observations")
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Track when a filing gap stops pausing setups
|
||||
|
||||
Revision ID: 034
|
||||
Revises: 033
|
||||
Create Date: 2026-08-21 00:00:00.000000
|
||||
|
||||
An escalated gap stops pausing setups while the issuer's own fundamentals are
|
||||
still recent (``GAP_GATE_RECENT_FILING_DAYS``). That reprieve is not permanent:
|
||||
the stored filings age out, or a newer gap appears, and the pause returns —
|
||||
silently, because ``filing_gap_aged`` only escalates gaps whose ``escalated_at``
|
||||
is NULL and so never fires twice for the same gap.
|
||||
|
||||
``exempted_at`` is the state marker that makes the transition observable. It is
|
||||
set (quietly) while the issuer is exempt and cleared when the exemption lapses,
|
||||
which is when ``filing_gap_repaused`` fires — once per lapse, re-arming if the
|
||||
issuer's data recovers and ages out again.
|
||||
|
||||
Nullable, and carrying no meaning of its own beyond that state: an existing gap
|
||||
starts NULL and is stamped on the next import that finds it exempt.
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "034"
|
||||
down_revision: Union[str, None] = "033"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
"sec_filing_gaps",
|
||||
sa.Column("exempted_at", sa.DateTime(timezone=True), nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("sec_filing_gaps", "exempted_at")
|
||||
+25
-17
@@ -28,16 +28,31 @@ class Settings(BaseSettings):
|
||||
deepseek_api_key: str = ""
|
||||
xai_api_key: str = ""
|
||||
|
||||
# Fundamentals Provider — Financial Modeling Prep
|
||||
fmp_api_key: str = ""
|
||||
# Dolt bulk-data — local clone of post-no-preference/earnings (workstream A).
|
||||
# dolt_binary: full path when not on PATH (dev/Windows install). dolt_data_dir
|
||||
# holds the clones; in production it MUST be outside the deploy tree (deploy is
|
||||
# rsync --delete) — set DOLT_DATA_DIR to a persistent path. The earnings clone
|
||||
# lives at <dolt_data_dir>/<dolt_earnings_subdir>.
|
||||
dolt_binary: str = "dolt"
|
||||
dolt_data_dir: str = "dolt-data"
|
||||
dolt_earnings_subdir: str = "earnings"
|
||||
# Headroom above the ~1.7 GB earnings clone (grows with pulls); 5 GB is a safe
|
||||
# production floor — override lower only in a space-constrained dev box.
|
||||
dolt_min_free_disk_gb: float = 5.0
|
||||
# Bound every dolt subprocess so a hung pull/sql can't pin the import's
|
||||
# connection + advisory lock indefinitely.
|
||||
dolt_command_timeout_seconds: float = 600.0
|
||||
|
||||
# Fundamentals Provider — Finnhub (optional fallback)
|
||||
finnhub_api_key: str = ""
|
||||
# SEC EDGAR (workstream A, fundamentals). Fair-access policy REQUIRES an
|
||||
# identifying User-Agent with a contact email — set a real one. Stay well
|
||||
# under 10 req/s (spacing below); 403 means the UA/pattern is wrong → the
|
||||
# client alerts and stops rather than retry-looping.
|
||||
sec_user_agent: str = "signal-platform/1.0 (contact: set-a-real-email@example.com)"
|
||||
sec_request_spacing_seconds: float = 0.2
|
||||
sec_max_retries: int = 4
|
||||
sec_request_timeout_seconds: float = 30.0
|
||||
|
||||
# Fundamentals Provider — Alpha Vantage (optional fallback)
|
||||
alpha_vantage_api_key: str = ""
|
||||
|
||||
# Regime Monitor — FRED (VIX level + HY credit spreads). Optional: without it
|
||||
# AI/Tech Risk Monitor — FRED (VIX level + HY credit spreads). Optional: without it
|
||||
# the volatility (P5) and credit-spread (F2) signals are reported as n/a.
|
||||
fred_api_key: str = ""
|
||||
|
||||
@@ -58,15 +73,8 @@ class Settings(BaseSettings):
|
||||
# the score window is 7 days).
|
||||
sentiment_fresh_hours: int = 120
|
||||
sentiment_top_composite: int = 30
|
||||
fundamental_fetch_frequency: str = "weekly" # quarterly-ish data; weekly conserves API quota
|
||||
rr_scan_frequency: str = "daily"
|
||||
alerts_frequency: str = "hourly"
|
||||
fundamental_rate_limit_retries: int = 3
|
||||
fundamental_rate_limit_backoff_seconds: int = 15
|
||||
# Pause between tickers in the bulk fundamentals job. Free tiers throttle
|
||||
# hard (Finnhub ~60 calls/min, ~3 calls/ticker → ~3s/ticker); without
|
||||
# spacing the job bursts straight into 429s. 0 disables.
|
||||
fundamental_request_spacing_seconds: float = 3.0
|
||||
rr_scan_frequency: str = "daily" # legacy label; qualifying scan is cron near-close
|
||||
# alerts_frequency removed: alerts fire only via morning + near-close pipelines
|
||||
|
||||
# Scoring Defaults
|
||||
default_watchlist_auto_size: int = 10
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Job topology: names, labels, pipeline membership, categories, ordering.
|
||||
|
||||
The single source of truth for *what the jobs are*, as opposed to how they run.
|
||||
It deliberately imports nothing from ``app`` so both ``app.scheduler`` and
|
||||
``app.services.admin_service`` can import it at module level -- admin_service
|
||||
otherwise has to do ``from app.scheduler import ...`` inside functions to dodge a
|
||||
cycle.
|
||||
|
||||
The pipeline step lists live here rather than in the scheduler because three
|
||||
separate things need them and used to keep private copies: the runner, the
|
||||
``PIPELINE_MEMBERS`` set the admin API reports, and the UI's grouping. Steps are
|
||||
``(step_name, coroutine_name)``; ``_run_pipeline`` resolves the coroutine late
|
||||
out of the scheduler's own globals, so nothing here depends on those functions
|
||||
existing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pipelines
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_DAILY_PIPELINE_STEPS = [
|
||||
("data_collector", "collect_ohlcv"),
|
||||
("benchmark_collector", "collect_benchmark"),
|
||||
("sentiment_collector", "collect_sentiment"),
|
||||
("market_regime", "compute_market_regime"),
|
||||
# Observational only — display/alerts; not trade selection.
|
||||
("regime_monitor", "compute_regime_monitor"),
|
||||
# Alerts after regime so quadrant changes reach Telegram in the morning.
|
||||
# Dispatcher is change-driven; quiet days stay quiet. Setup alerts still
|
||||
# fire on the near-close pipeline after the qualifying scan.
|
||||
("alerts", "dispatch_alerts_job"),
|
||||
]
|
||||
|
||||
# Near-close (~15:30 ET Mon–Fri): refresh in-progress day-t bars (incremental
|
||||
# ingestion overlaps the latest stored session), then the only daily
|
||||
# qualifying R:R scan, then Telegram immediately so manual fills can still hit
|
||||
# MOC cutoffs (~15:50/15:55). Under a 15-minute delayed SIP feed a 15:30 scan
|
||||
# may see ~15:15 prices — immaterial for a 12-1 momentum signal.
|
||||
#
|
||||
# US early-close days (~3/year, 13:00 ET close): this job runs post-close and
|
||||
# entries behave like stale_close (still acceptable per execution-recovery matrix).
|
||||
# No exchange calendar dependency.
|
||||
_NEAR_CLOSE_PIPELINE_STEPS = [
|
||||
# Must land today's in-progress bar (~20 min behind live), or the scan falls
|
||||
# back to the previous close and execution degrades to the stale_close floor.
|
||||
("data_collector", "collect_ohlcv_for_scan"),
|
||||
("rr_scanner", "scan_rr"),
|
||||
# Straight after the scan so shadow entries mark at the same near-close
|
||||
# prices the discretionary book is looking at.
|
||||
("shadow_book", "run_shadow_book"),
|
||||
("alerts", "dispatch_alerts_job"),
|
||||
]
|
||||
|
||||
# After close (~16:45 ET Mon–Fri): fresh OHLCV fetch so outcomes resolve on the
|
||||
# final bar, not the near-close partial bar, then outcome/paper close.
|
||||
_AFTER_CLOSE_PIPELINE_STEPS = [
|
||||
("data_collector", "collect_ohlcv_final"),
|
||||
("outcome_evaluator", "evaluate_outcomes"),
|
||||
]
|
||||
|
||||
# Intraday (light): keep prices current and resolve outcomes through the day,
|
||||
# without the expensive scan/sentiment. The dashboard recomputes live R:R from
|
||||
# the latest price, so refreshing OHLCV is enough to stop prices lagging; the
|
||||
# outcome step also closes paper trades that hit their stop/target intraday.
|
||||
_INTRADAY_PIPELINE_STEPS = [
|
||||
("data_collector", "collect_ohlcv"),
|
||||
("outcome_evaluator", "evaluate_outcomes"),
|
||||
]
|
||||
|
||||
# Ordered by trading day, not alphabetically: this is the sequence an operator
|
||||
# reads down the page, and it drives the UI's ordering too.
|
||||
PIPELINE_STEPS: dict[str, list[tuple[str, str]]] = {
|
||||
"daily_pipeline": _DAILY_PIPELINE_STEPS,
|
||||
"intraday_pipeline": _INTRADAY_PIPELINE_STEPS,
|
||||
"near_close_pipeline": _NEAR_CLOSE_PIPELINE_STEPS,
|
||||
"after_close_pipeline": _AFTER_CLOSE_PIPELINE_STEPS,
|
||||
}
|
||||
|
||||
# Derived, never hand-maintained: this used to be a literal set in admin_service
|
||||
# duplicating the four lists above from another module, with nothing asserting
|
||||
# the two agreed.
|
||||
PIPELINE_MEMBERS: frozenset[str] = frozenset(
|
||||
step for steps in PIPELINE_STEPS.values() for step, _ in steps
|
||||
)
|
||||
|
||||
|
||||
def _pipelines_by_member() -> dict[str, tuple[str, ...]]:
|
||||
"""Member -> the orchestrators that run it, in trading-day order.
|
||||
|
||||
Membership is many-to-many: data_collector runs in all four pipelines (via
|
||||
three different coroutines), alerts and outcome_evaluator in two each.
|
||||
"""
|
||||
out: dict[str, list[str]] = {}
|
||||
for pipeline, steps in PIPELINE_STEPS.items():
|
||||
for step, _ in steps:
|
||||
bucket = out.setdefault(step, [])
|
||||
if pipeline not in bucket:
|
||||
bucket.append(pipeline)
|
||||
return {member: tuple(pipelines) for member, pipelines in out.items()}
|
||||
|
||||
|
||||
PIPELINES_BY_MEMBER: dict[str, tuple[str, ...]] = _pipelines_by_member()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job identity
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Orchestrators, in trading-day order.
|
||||
PIPELINE_JOBS: tuple[str, ...] = tuple(PIPELINE_STEPS)
|
||||
|
||||
# Own timer, independent of any pipeline.
|
||||
SCHEDULED_JOBS: tuple[str, ...] = (
|
||||
"dolt_earnings_import",
|
||||
"sec_fundamentals_import",
|
||||
"ticker_universe_sync",
|
||||
"backtest",
|
||||
)
|
||||
|
||||
# Registered but never auto-fired; run only when a human asks.
|
||||
MANUAL_JOBS: tuple[str, ...] = ("event_study", "data_backfill")
|
||||
|
||||
# Steps in the order an operator meets them across the trading day, so the UI
|
||||
# reads as a sequence rather than an alphabetical jumble.
|
||||
PIPELINE_STEP_JOBS: tuple[str, ...] = tuple(
|
||||
dict.fromkeys(step for steps in PIPELINE_STEPS.values() for step, _ in steps)
|
||||
)
|
||||
|
||||
VALID_JOB_NAMES: frozenset[str] = frozenset(
|
||||
PIPELINE_JOBS + PIPELINE_STEP_JOBS + SCHEDULED_JOBS + MANUAL_JOBS
|
||||
)
|
||||
|
||||
JOB_LABELS: dict[str, str] = {
|
||||
"data_collector": "Data Collector (OHLCV)",
|
||||
"data_backfill": "Data Backfill (deep history)",
|
||||
"benchmark_collector": "Benchmark Collector",
|
||||
"sentiment_collector": "Sentiment Collector",
|
||||
"dolt_earnings_import": "Dolt Earnings Import",
|
||||
"sec_fundamentals_import": "SEC Fundamentals Import",
|
||||
"rr_scanner": "R:R Scanner",
|
||||
"ticker_universe_sync": "Ticker Universe Sync",
|
||||
"outcome_evaluator": "Outcome Evaluator",
|
||||
"alerts": "Alerts Dispatcher",
|
||||
# Keys are persisted job ids and must not change; these are display only.
|
||||
"market_regime": "Market Trend (SPY)",
|
||||
"regime_monitor": "AI/Tech Risk Monitor",
|
||||
"event_study": "Event Study",
|
||||
"backtest": "Backtest",
|
||||
"daily_pipeline": "Morning Pipeline",
|
||||
"near_close_pipeline": "Near-Close Pipeline (scan+alert)",
|
||||
"after_close_pipeline": "After-Close Pipeline (outcome)",
|
||||
"intraday_pipeline": "Intraday Pipeline",
|
||||
"shadow_book": "Shadow Book (auto-traded strategy)",
|
||||
}
|
||||
|
||||
CATEGORY_PIPELINE = "pipeline"
|
||||
CATEGORY_STEP = "pipeline_step"
|
||||
CATEGORY_SCHEDULED = "scheduled"
|
||||
CATEGORY_MANUAL = "manual"
|
||||
|
||||
# Order the sections appear in.
|
||||
CATEGORY_ORDER: tuple[str, ...] = (
|
||||
CATEGORY_PIPELINE,
|
||||
CATEGORY_STEP,
|
||||
CATEGORY_SCHEDULED,
|
||||
CATEGORY_MANUAL,
|
||||
)
|
||||
|
||||
CATEGORY_LABELS: dict[str, str] = {
|
||||
CATEGORY_PIPELINE: "Pipelines",
|
||||
CATEGORY_STEP: "Pipeline steps",
|
||||
CATEGORY_SCHEDULED: "Standalone scheduled",
|
||||
CATEGORY_MANUAL: "Manual only",
|
||||
}
|
||||
|
||||
_CATEGORY_MEMBERS: dict[str, tuple[str, ...]] = {
|
||||
CATEGORY_PIPELINE: PIPELINE_JOBS,
|
||||
CATEGORY_STEP: PIPELINE_STEP_JOBS,
|
||||
CATEGORY_SCHEDULED: SCHEDULED_JOBS,
|
||||
CATEGORY_MANUAL: MANUAL_JOBS,
|
||||
}
|
||||
|
||||
JOB_CATEGORY: dict[str, str] = {
|
||||
name: category
|
||||
for category, names in _CATEGORY_MEMBERS.items()
|
||||
for name in names
|
||||
}
|
||||
|
||||
# Registered and triggerable through the API, but kept out of Admin → Jobs.
|
||||
# data_backfill's only capability beyond collect_ohlcv (which already backfills
|
||||
# full history for *new* tickers) is re-deepening *existing* ones after
|
||||
# ohlcv_history_days is raised -- a rare one-off, not something to scan past
|
||||
# every time you open the page.
|
||||
HIDDEN_JOBS: frozenset[str] = frozenset({"data_backfill"})
|
||||
|
||||
_SORT_INDEX: dict[str, tuple[int, int]] = {
|
||||
name: (CATEGORY_ORDER.index(category), position)
|
||||
for category, names in _CATEGORY_MEMBERS.items()
|
||||
for position, name in enumerate(names)
|
||||
}
|
||||
|
||||
|
||||
def sort_order(job_name: str) -> tuple[int, int]:
|
||||
"""(category rank, position within category). Unknown jobs sort last."""
|
||||
return _SORT_INDEX.get(job_name, (len(CATEGORY_ORDER), 0))
|
||||
+11
-50
@@ -3,56 +3,9 @@
|
||||
# ---------------------------------------------------------------------------
|
||||
# SSL + proxy injection — MUST happen before any HTTP client imports
|
||||
# ---------------------------------------------------------------------------
|
||||
import os as _os
|
||||
import ssl as _ssl
|
||||
from pathlib import Path as _Path
|
||||
from app.ssl_bootstrap import bootstrap_ssl
|
||||
|
||||
_COMBINED_CERT = _Path(__file__).resolve().parent.parent / "combined-ca-bundle.pem"
|
||||
|
||||
if _COMBINED_CERT.exists():
|
||||
_cert_path = str(_COMBINED_CERT)
|
||||
# Env vars for libraries that respect them (requests, urllib3)
|
||||
_os.environ["SSL_CERT_FILE"] = _cert_path
|
||||
_os.environ["REQUESTS_CA_BUNDLE"] = _cert_path
|
||||
_os.environ["CURL_CA_BUNDLE"] = _cert_path
|
||||
|
||||
# Monkey-patch ssl.create_default_context so that ALL libraries
|
||||
# (aiohttp, httpx, google-genai, alpaca-py, etc.) automatically
|
||||
# use our combined CA bundle that includes the corporate root cert.
|
||||
_original_create_default_context = _ssl.create_default_context
|
||||
|
||||
def _patched_create_default_context(
|
||||
purpose=_ssl.Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None
|
||||
):
|
||||
ctx = _original_create_default_context(
|
||||
purpose, cafile=cafile, capath=capath, cadata=cadata
|
||||
)
|
||||
# Always load our combined bundle on top of whatever was loaded
|
||||
ctx.load_verify_locations(cafile=_cert_path)
|
||||
return ctx
|
||||
|
||||
_ssl.create_default_context = _patched_create_default_context
|
||||
|
||||
# Also patch aiohttp's cached SSL context objects directly, since
|
||||
# aiohttp creates them at import time and may have already cached
|
||||
# a context without our corporate CA bundle.
|
||||
try:
|
||||
import aiohttp.connector as _aio_conn
|
||||
if hasattr(_aio_conn, '_SSL_CONTEXT_VERIFIED') and _aio_conn._SSL_CONTEXT_VERIFIED is not None:
|
||||
_aio_conn._SSL_CONTEXT_VERIFIED.load_verify_locations(cafile=_cert_path)
|
||||
if hasattr(_aio_conn, '_SSL_CONTEXT_UNVERIFIED') and _aio_conn._SSL_CONTEXT_UNVERIFIED is not None:
|
||||
_aio_conn._SSL_CONTEXT_UNVERIFIED.load_verify_locations(cafile=_cert_path)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Corporate proxy — needed when Kiro spawns the process (no .zshrc sourced)
|
||||
# Only enable this if explicitly requested via environment variable.
|
||||
if _os.environ.get("USE_CORP_PROXY", "0") == "1":
|
||||
_PROXY = "http://aproxy.corproot.net:8080"
|
||||
_NO_PROXY = "corproot.net,sharedtcs.net,127.0.0.1,localhost,bix.swisscom.com,swisscom.com"
|
||||
_os.environ.setdefault("HTTP_PROXY", _PROXY)
|
||||
_os.environ.setdefault("HTTPS_PROXY", _PROXY)
|
||||
_os.environ.setdefault("NO_PROXY", _NO_PROXY)
|
||||
bootstrap_ssl()
|
||||
|
||||
import logging
|
||||
import sys
|
||||
@@ -68,7 +21,12 @@ from app.config import settings
|
||||
from app.database import async_session_factory, engine
|
||||
from app.middleware import register_exception_handlers
|
||||
from app.models.user import User
|
||||
from app.scheduler import configure_scheduler, load_schedule_config, scheduler
|
||||
from app.scheduler import (
|
||||
configure_scheduler,
|
||||
flush_job_run_persists,
|
||||
load_schedule_config,
|
||||
scheduler,
|
||||
)
|
||||
from app.routers.admin import router as admin_router
|
||||
from app.routers.auth import router as auth_router
|
||||
from app.routers.health import router as health_router
|
||||
@@ -138,6 +96,9 @@ async def lifespan(_app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
|
||||
scheduler.shutdown(wait=False)
|
||||
logger.info("Scheduler stopped")
|
||||
# Drain detached last-run writes before the engine goes away, or a job that
|
||||
# finished during shutdown loses the row it just wrote.
|
||||
await flush_job_run_persists()
|
||||
await engine.dispose()
|
||||
logger.info("Shutting down")
|
||||
|
||||
|
||||
@@ -3,6 +3,9 @@ from app.models.ohlcv import OHLCVRecord
|
||||
from app.models.user import User
|
||||
from app.models.sentiment import SentimentScore
|
||||
from app.models.fundamental import FundamentalData
|
||||
from app.models.fundamental_snapshot import FundamentalSnapshot
|
||||
from app.models.earnings_event import EarningsEvent
|
||||
from app.models.data_import_run import DataImportRun
|
||||
from app.models.score import DimensionScore, CompositeScore
|
||||
from app.models.sr_level import SRLevel
|
||||
from app.models.trade_setup import TradeSetup
|
||||
@@ -11,8 +14,12 @@ from app.models.settings import SystemSetting, IngestionProgress
|
||||
from app.models.alert import AlertLog
|
||||
from app.models.paper_trade import PaperTrade
|
||||
from app.models.regime_snapshot import RegimeSnapshot
|
||||
from app.models.regime_fundamental_observation import RegimeFundamentalObservation
|
||||
from app.models.benchmark_price import BenchmarkPrice
|
||||
from app.models.signal_context_snapshot import SignalContextSnapshot
|
||||
from app.models.system_event import SystemEvent
|
||||
from app.models.sec_filing_gap import SecFilingGap
|
||||
from app.models.job_run_state import JobRunState
|
||||
|
||||
__all__ = [
|
||||
"Ticker",
|
||||
@@ -20,6 +27,9 @@ __all__ = [
|
||||
"User",
|
||||
"SentimentScore",
|
||||
"FundamentalData",
|
||||
"FundamentalSnapshot",
|
||||
"EarningsEvent",
|
||||
"DataImportRun",
|
||||
"DimensionScore",
|
||||
"CompositeScore",
|
||||
"SRLevel",
|
||||
@@ -30,6 +40,10 @@ __all__ = [
|
||||
"AlertLog",
|
||||
"PaperTrade",
|
||||
"RegimeSnapshot",
|
||||
"RegimeFundamentalObservation",
|
||||
"BenchmarkPrice",
|
||||
"SignalContextSnapshot",
|
||||
"SystemEvent",
|
||||
"SecFilingGap",
|
||||
"JobRunState",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import Date, DateTime, Index, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class DataImportRun(Base):
|
||||
"""One row per bulk-import attempt (SEC facts / Dolt earnings / Dolt stocks).
|
||||
|
||||
Lean audit record for the batch import framework: every attempt is logged,
|
||||
whether it promoted, was a ``no_op`` (unchanged revision), was ``deferred``
|
||||
for an expected retry, or ``failed``.
|
||||
``row_counts`` and ``validation`` hold JSON strings (repo convention — see
|
||||
``fundamental_data.unavailable_fields_json``), not JSONB; the validation
|
||||
blob carries reconciliation/discrepancy summaries so no separate conflicts
|
||||
table is needed. One run per source at a time is enforced at write time by a
|
||||
Postgres advisory lock keyed by ``source``.
|
||||
"""
|
||||
|
||||
__tablename__ = "data_import_runs"
|
||||
__table_args__ = (
|
||||
Index("ix_data_import_runs_source_started", "source", "started_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# sec_facts | dolt_earnings | dolt_stocks
|
||||
source: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
# Dolt commit hash, or SEC archive SHA-256. Null until known.
|
||||
revision: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
# running | validated | promoted | no_op | deferred | failed
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
source_max_date: Mapped[date | None] = mapped_column(Date, nullable=True)
|
||||
row_counts_json: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
validation_json: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
started_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=datetime.utcnow, nullable=False
|
||||
)
|
||||
completed_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
# Failure detail, or the non-error reason when status is deferred.
|
||||
error_details: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
@@ -0,0 +1,42 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import Date, DateTime, Float, ForeignKey, Index, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class EarningsEvent(Base):
|
||||
"""Earnings calendar + surprise history, sourced from the DoltHub earnings repo.
|
||||
|
||||
Forward rows (``announce_date`` > today) are the calendar; past rows are
|
||||
results. Rescheduling is handled in the importer's promotion transaction:
|
||||
this source's future-dated rows are deleted and re-inserted from the new
|
||||
snapshot so moved/cancelled dates never linger; past rows are never deleted.
|
||||
"""
|
||||
|
||||
__tablename__ = "earnings_events"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("ticker_id", "announce_date", name="uq_earnings_ticker_announce"),
|
||||
Index("ix_earnings_events_announce_date", "announce_date"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
ticker_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("tickers.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
announce_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
# bmo | amc | unknown (source coverage is partial)
|
||||
session: Mapped[str] = mapped_column(String(10), nullable=False, default="unknown")
|
||||
period_end: Mapped[date | None] = mapped_column(Date, nullable=True)
|
||||
eps_estimate: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
eps_actual: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
source: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
import_run_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("data_import_runs.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=datetime.utcnow, nullable=False
|
||||
)
|
||||
|
||||
ticker = relationship("Ticker", back_populates="earnings_events")
|
||||
@@ -0,0 +1,87 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import Date, DateTime, Float, ForeignKey, Index, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class FundamentalSnapshot(Base):
|
||||
"""CIK-keyed, one immutable row per SEC accession.
|
||||
|
||||
Keyed by issuer (CIK), not ticker — multi-class issuers (GOOG/GOOGL) share
|
||||
one CIK and one set of fundamentals; the ``tickers.cik`` column is the only
|
||||
join point. Amendments are retained: every accession is a distinct immutable
|
||||
row, and readers resolve (cik, fiscal_year, fiscal_period) at read time by
|
||||
taking the newest ``accepted_at`` **per field**, falling back to the newest
|
||||
accession that actually reports one — a partial amendment (a 10-K/A adding
|
||||
Part III reports no financial facts) must not blank the period — no flags, no mutation.
|
||||
|
||||
**Facts are stored as the filing reports them, never as derived quarters.**
|
||||
Duration facts (revenue, net_income, operating_income, diluted_eps, cfo,
|
||||
capex, depreciation_amortization) hold the filing's normalized **cumulative
|
||||
YTD/FY** value over (period_start -> period_end). Balance-sheet facts
|
||||
(cash_and_st_investments, total_debt, shares_outstanding) are **period-end**
|
||||
values. ``shares_outstanding`` is a single consolidated point-in-time count —
|
||||
the ``dei:EntityCommonStockSharesOutstanding`` cover-page fact, or
|
||||
``us-gaap:CommonStockSharesOutstanding`` at period end when no dei fact exists
|
||||
(e.g. Alphabet). It is never a class sum (companyfacts is non-dimensional) nor
|
||||
the weighted-average diluted count, since both consumers (estimated market cap,
|
||||
YoY dilution read) want a point-in-time value. Discrete quarters (10-Q YTD
|
||||
deltas, Q4 = FY - Q1..Q3), TTM, YoY and
|
||||
the quarter tape are all derived at read time — so non-calendar fiscal years
|
||||
resolve correctly and a later amendment never leaves a stale frozen quarter.
|
||||
"""
|
||||
|
||||
__tablename__ = "fundamental_snapshots"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("accession", name="uq_fundamental_snapshots_accession"),
|
||||
Index("ix_fundamental_snapshots_cik_period", "cik", "fiscal_year", "fiscal_period"),
|
||||
Index("ix_fundamental_snapshots_cik_period_end", "cik", "period_end"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
cik: Mapped[str] = mapped_column(String(10), nullable=False)
|
||||
accession: Mapped[str] = mapped_column(String(25), nullable=False)
|
||||
form: Mapped[str] = mapped_column(String(12), nullable=False) # 10-Q, 10-K, 10-K/A ...
|
||||
filed_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
# Kept although PIT enforcement is deferred (one timestamp now vs painful retrofit).
|
||||
accepted_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
|
||||
# Period identity — required to align non-calendar fiscal years and to derive
|
||||
# discrete quarters from cumulative facts.
|
||||
period_start: Mapped[date | None] = mapped_column(Date, nullable=True)
|
||||
period_end: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
fiscal_year: Mapped[int] = mapped_column(nullable=False)
|
||||
fiscal_period: Mapped[str] = mapped_column(String(4), nullable=False) # Q1|Q2|Q3|Q4|FY
|
||||
|
||||
# Duration facts — cumulative YTD/FY over (period_start -> period_end).
|
||||
revenue: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
net_income: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
operating_income: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
diluted_eps: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
cfo: Mapped[float | None] = mapped_column(Float, nullable=True) # cash flow from operations
|
||||
capex: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
depreciation_amortization: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
|
||||
# Balance-sheet facts — period-end values.
|
||||
cash_and_st_investments: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
total_debt: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
shares_outstanding: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
# The cover-page share count (dei:EntityCommonStockSharesOutstanding) is
|
||||
# reported "as of" its own date, which can differ from period_end — store it
|
||||
# so market cap uses the right point-in-time count.
|
||||
shares_outstanding_date: Mapped[date | None] = mapped_column(Date, nullable=True)
|
||||
# Weighted-average diluted count for the filing's most recent quarter — the
|
||||
# market-cap fallback when the cover-page count is absent, which it always is
|
||||
# for multi-class issuers (per-class facts are dimensional, and companyfacts
|
||||
# is not). An average is not cumulative, so unlike the duration facts above
|
||||
# this is NOT a YTD value: it is the shortest-span fact ending at period_end.
|
||||
weighted_avg_diluted_shares: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
|
||||
import_run_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("data_import_runs.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=datetime.utcnow, nullable=False
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class JobRunState(Base):
|
||||
"""How each scheduled job last finished. One row per job, overwritten.
|
||||
|
||||
The scheduler's ``_job_runtime`` dict is the live view and is deliberately
|
||||
in-memory, but it is also wiped by every process restart -- so after a deploy
|
||||
Admin → Jobs could only say "Active" with no indication of whether a job had
|
||||
ever run. This is the durable half.
|
||||
|
||||
Deliberately not history: ``system_events`` already grows without a reaper,
|
||||
and a second append-only operational table would repeat that. Rows are
|
||||
upserted on ``job_name``; adding history later is purely additive.
|
||||
"""
|
||||
|
||||
__tablename__ = "job_run_state"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
job_name: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
||||
# Scheduler vocabulary: completed | skipped | error | rate_limited | deferred.
|
||||
# Distinct from data_import_runs' statuses, which is one reason this is its
|
||||
# own table rather than a widened column there.
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
finished_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
processed: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
total: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
message: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
|
||||
)
|
||||
@@ -36,3 +36,25 @@ class PaperTrade(Base):
|
||||
closed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
# How the trade was closed: "time" | "trailing" | "stop" | "target" | "manual".
|
||||
close_reason: Mapped[str | None] = mapped_column(String(10), nullable=True)
|
||||
# A trade stopped at its initial stop starts a re-entry gate-reset episode.
|
||||
# The daily full-universe scanner records both state transitions: the first
|
||||
# failed gate observation and a later fresh qualification. Re-entry remains
|
||||
# non-actionable until both timestamps exist.
|
||||
reentry_gate_failed_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
reentry_gate_requalified_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
# Execution era for forward vs backtest comparison:
|
||||
# null/legacy = pre-cutover morning-scan, "near_close" = post near-close cutover.
|
||||
fill_mode: Mapped[str | None] = mapped_column(String(20), nullable=True)
|
||||
# Which book this trade belongs to:
|
||||
# "manual" — discretionary, opened by the user from a qualified setup
|
||||
# "shadow" — opened automatically by the validated strategy (top-ranked
|
||||
# qualified up to capacity, 1% risk). The shadow book is the
|
||||
# faithful live twin of the backtest; the two books share the
|
||||
# same exit policy so the only difference is *selection*.
|
||||
# Gate-reset re-entry state is tracked per book — the books diverge as soon
|
||||
# as their entries differ, and each must see its own trade history.
|
||||
book: Mapped[str] = mapped_column(String(10), nullable=False, default="manual")
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
from datetime import date as date_type
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Date, DateTime, Float, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class RegimeFundamentalObservation(Base):
|
||||
"""Point-in-time record of the sourced hyperscaler capex / earnings read.
|
||||
|
||||
One row per ``effective_date`` (unique, upserted). Before this table the
|
||||
observation lived in a single ``SystemSetting`` slot, so every refresh
|
||||
overwrote the previous one and no history existed at all — which made the
|
||||
read impossible to replay, impossible to backtest, and meant a snapshot
|
||||
rebuild could only ever score historical sessions as if nothing had been
|
||||
observed.
|
||||
|
||||
The read is a categorical channel reported beside State and Warning, never a
|
||||
term in either, so this series is not a scoring input. It is the record that
|
||||
makes the channel replayable at all -- and the only route to eventually
|
||||
testing whether it improves prediction conditional on Warning, which is the
|
||||
one thing that could justify combining the channels later.
|
||||
|
||||
``effective_date`` rather than ``fetched_at`` is the key: it is the session
|
||||
the observation becomes usable on (normally the next weekday), and the gate
|
||||
that stops a rebuild stamping today's reading onto historical rows.
|
||||
"""
|
||||
|
||||
__tablename__ = "regime_fundamental_observations"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
effective_date: Mapped[date_type] = mapped_column(
|
||||
Date, nullable=False, unique=True, index=True
|
||||
)
|
||||
f1_score: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
f3_score: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
capex_json: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
good_news_stock_down: Mapped[str] = mapped_column(String(10), nullable=False)
|
||||
reasoning: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
source: Mapped[str] = mapped_column(String(30), nullable=False)
|
||||
fetched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
@@ -8,12 +8,12 @@ from app.database import Base
|
||||
|
||||
|
||||
class RegimeSnapshot(Base):
|
||||
"""Daily snapshot of the AI/Tech regime-change index.
|
||||
"""Daily point-in-time snapshot of the AI/Tech Risk Monitor.
|
||||
|
||||
One row per calendar date (unique). ``breakdown_json`` holds the full
|
||||
per-signal breakdown plus the raw inputs, so reads need no recomputation and
|
||||
the 7/30-day trend is just a query over ``total_score``. Decoupled from the
|
||||
rest of the platform: nothing reads this to gate or score trades.
|
||||
``breakdown_json`` is authoritative for v2 State, Warning, source dates,
|
||||
coverage, and fixed-basket metadata. ``total_score``/``band`` retain the v2
|
||||
State reading for schema compatibility. Nothing reads this to gate trades.
|
||||
"""
|
||||
|
||||
__tablename__ = "regime_snapshots"
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import Date, DateTime, Index, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class SecFilingGap(Base):
|
||||
"""Active SEC filing that could not yet be reconstructed.
|
||||
|
||||
Rows form a small retry queue. Successful snapshot ingestion deletes the
|
||||
matching row; a later valid filing supersedes it. While a current row remains,
|
||||
tickers mapped to its CIK are not eligible for actionable trade setups.
|
||||
"""
|
||||
|
||||
__tablename__ = "sec_filing_gaps"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("accession", name="uq_sec_filing_gaps_accession"),
|
||||
Index("ix_sec_filing_gaps_cik", "cik"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
cik: Mapped[str] = mapped_column(String(10), nullable=False)
|
||||
accession: Mapped[str] = mapped_column(String(25), nullable=False)
|
||||
form: Mapped[str | None] = mapped_column(String(12), nullable=True)
|
||||
index_date: Mapped[date | None] = mapped_column(Date, nullable=True)
|
||||
reason: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
coregistrant_ciks_json: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
first_seen_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
last_attempted_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
escalated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
# Set while this gap's issuer is exempt from the setup pause (escalated, and
|
||||
# its own fundamentals still recent — see fundamentals_quality_service).
|
||||
# Cleared when the exemption lapses, which is the moment the pause silently
|
||||
# comes back and the only moment worth alerting on.
|
||||
exempted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Operational system events (warnings/errors) for the admin UI and top-nav badge."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, Index, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class SystemEvent(Base):
|
||||
"""Durable warning/error record (jobs, ingestion, pipelines).
|
||||
|
||||
``acknowledged_at`` is set when a user dismisses the nav badge / clears
|
||||
events — history still shows in Admin → Jobs for the retention window.
|
||||
"""
|
||||
|
||||
__tablename__ = "system_events"
|
||||
__table_args__ = (
|
||||
Index("ix_system_events_created_at", "created_at"),
|
||||
Index("ix_system_events_ack_created", "acknowledged_at", "created_at"),
|
||||
Index("ix_system_events_dedup_created", "dedup_key", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
severity: Mapped[str] = mapped_column(String(16), nullable=False) # warning | error
|
||||
source: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
message: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
symbol: Mapped[str | None] = mapped_column(String(20), nullable=True)
|
||||
dedup_key: Mapped[str | None] = mapped_column(String(200), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=datetime.utcnow, nullable=False
|
||||
)
|
||||
acknowledged_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
+17
-2
@@ -1,6 +1,6 @@
|
||||
from datetime import datetime
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import String, DateTime
|
||||
from sqlalchemy import Date, String, DateTime
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.database import Base
|
||||
@@ -14,6 +14,20 @@ class Ticker(Base):
|
||||
# Company name (e.g. "Biogen Inc."); backfilled from Alpaca, nullable for
|
||||
# symbols Alpaca doesn't know.
|
||||
name: Mapped[str | None] = mapped_column(String(120), nullable=True)
|
||||
# SEC issuer identity, refreshed by the SEC fundamentals import from
|
||||
# company_tickers.json / submissions. The only ticker<->issuer join point;
|
||||
# multi-class tickers (GOOG/GOOGL) share these values. Nullable: not every
|
||||
# symbol resolves to a CIK (e.g. ADRs, foreign issuers not in SEC data).
|
||||
cik: Mapped[str | None] = mapped_column(String(10), nullable=True)
|
||||
sic: Mapped[str | None] = mapped_column(String(4), nullable=True)
|
||||
sic_description: Mapped[str | None] = mapped_column(String(160), nullable=True)
|
||||
# Delisting is recorded, never deleted: the rows carry the price history that
|
||||
# makes a backtest less survivorship-biased, and a delete cascades it away.
|
||||
# NULL == actively traded. The live signal path filters on this (see
|
||||
# ticker_service.active_only); list/admin views keep the row and show it.
|
||||
delisted_on: Mapped[date | None] = mapped_column(Date, nullable=True, index=True)
|
||||
# How we learned: "form_25" (SEC confirmed), "manual" (operator).
|
||||
delisted_reason: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=datetime.utcnow, nullable=False
|
||||
)
|
||||
@@ -28,3 +42,4 @@ class Ticker(Base):
|
||||
trade_setups = relationship("TradeSetup", back_populates="ticker", cascade="all, delete-orphan")
|
||||
watchlist_entries = relationship("WatchlistEntry", back_populates="ticker", cascade="all, delete-orphan")
|
||||
ingestion_progress = relationship("IngestionProgress", back_populates="ticker", cascade="all, delete-orphan", uselist=False)
|
||||
earnings_events = relationship("EarningsEvent", back_populates="ticker", cascade="all, delete-orphan")
|
||||
|
||||
@@ -45,6 +45,11 @@ class TradeSetup(Base):
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
outcome_date: Mapped[date | None] = mapped_column(Date, nullable=True)
|
||||
# Identity of the scan run that produced this row. The shadow book selects
|
||||
# its batch by this id, not by a detected_at window, so a concurrent manual
|
||||
# scan writing rows in the same time window is excluded by identity. Null on
|
||||
# rows predating the column and on any non-scan creator.
|
||||
scan_run_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
|
||||
ticker = relationship("Ticker", back_populates="trade_setups")
|
||||
|
||||
|
||||
+31
-3
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import date
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
|
||||
from alpaca.data.historical import StockHistoricalDataClient
|
||||
from alpaca.data.requests import StockBarsRequest
|
||||
@@ -16,6 +16,11 @@ from app.providers.protocol import OHLCVData
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Free plans may not query data from the most recent ~15 minutes, and a window
|
||||
# reaching into it fails the *entire* request — which would silently leave the
|
||||
# near-close scan on yesterday's close. Margin over the documented boundary.
|
||||
_RECENT_DATA_CUTOFF = timedelta(minutes=20)
|
||||
|
||||
|
||||
class AlpacaOHLCVProvider:
|
||||
"""Fetches daily OHLCV bars from Alpaca Markets Data API."""
|
||||
@@ -25,6 +30,26 @@ class AlpacaOHLCVProvider:
|
||||
raise ProviderError("Alpaca API key and secret are required")
|
||||
self._client = StockHistoricalDataClient(api_key, api_secret)
|
||||
|
||||
@staticmethod
|
||||
def _resolve_window(start_date: date, end_date: date) -> tuple[datetime, datetime]:
|
||||
"""Return the instants covering ``start_date``..``end_date`` inclusive.
|
||||
|
||||
Two boundaries have to be right or today's bar disappears:
|
||||
|
||||
* Daily bars are stamped at the session start in UTC (04:00Z under EDT),
|
||||
so an ``end`` of midnight on ``end_date`` lands *before* that day's bar
|
||||
and silently drops it — extend to the following midnight instead.
|
||||
* The window must stay out of the delayed-data period, otherwise the
|
||||
request is rejected outright with "subscription does not permit
|
||||
querying recent SIP data". Clamping keeps today's in-progress bar
|
||||
available, roughly 20 minutes behind live.
|
||||
"""
|
||||
start = datetime.combine(start_date, time.min, tzinfo=timezone.utc)
|
||||
end = datetime.combine(
|
||||
end_date + timedelta(days=1), time.min, tzinfo=timezone.utc
|
||||
)
|
||||
return start, min(end, datetime.now(timezone.utc) - _RECENT_DATA_CUTOFF)
|
||||
|
||||
@staticmethod
|
||||
def _to_alpaca_symbol(symbol: str) -> str:
|
||||
"""Convert internal symbol format (BRK-B) to Alpaca format (BRK.B)."""
|
||||
@@ -40,12 +65,15 @@ class AlpacaOHLCVProvider:
|
||||
) -> list[OHLCVData]:
|
||||
"""Fetch daily OHLCV bars for *ticker* between *start_date* and *end_date*."""
|
||||
alpaca_symbol = self._to_alpaca_symbol(ticker)
|
||||
start, end = self._resolve_window(start_date, end_date)
|
||||
if end <= start:
|
||||
return []
|
||||
try:
|
||||
request = StockBarsRequest(
|
||||
symbol_or_symbols=alpaca_symbol,
|
||||
timeframe=TimeFrame.Day,
|
||||
start=start_date,
|
||||
end=end_date,
|
||||
start=start,
|
||||
end=end,
|
||||
adjustment=Adjustment.SPLIT,
|
||||
)
|
||||
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
"""Financial Modeling Prep (FMP) fundamentals provider using httpx.
|
||||
|
||||
Uses the stable API endpoints (https://financialmodelingprep.com/stable/)
|
||||
which replaced the legacy /api/v3/ endpoints deprecated in Aug 2025.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from app.exceptions import ProviderError, RateLimitError
|
||||
from app.providers.protocol import FundamentalData
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_FMP_STABLE_URL = "https://financialmodelingprep.com/stable"
|
||||
|
||||
# Resolve CA bundle for explicit httpx verify
|
||||
_CA_BUNDLE = os.environ.get("SSL_CERT_FILE", "")
|
||||
if not _CA_BUNDLE or not Path(_CA_BUNDLE).exists():
|
||||
_CA_BUNDLE_PATH: str | bool = True # use system default
|
||||
else:
|
||||
_CA_BUNDLE_PATH = _CA_BUNDLE
|
||||
|
||||
|
||||
class FMPFundamentalProvider:
|
||||
"""Fetches fundamental data from Financial Modeling Prep REST API."""
|
||||
|
||||
def __init__(self, api_key: str) -> None:
|
||||
if not api_key:
|
||||
raise ProviderError("FMP API key is required")
|
||||
self._api_key = api_key
|
||||
|
||||
# Mapping from FMP endpoint name to the FundamentalData field it populates
|
||||
_ENDPOINT_FIELD_MAP: dict[str, str] = {
|
||||
"ratios-ttm": "pe_ratio",
|
||||
"financial-growth": "revenue_growth",
|
||||
"earnings": "earnings_surprise",
|
||||
}
|
||||
|
||||
async def fetch_fundamentals(self, ticker: str) -> FundamentalData:
|
||||
"""Fetch P/E, revenue growth, earnings surprise, and market cap.
|
||||
|
||||
Fetches from multiple stable endpoints. If a supplementary endpoint
|
||||
(ratios, growth, earnings) returns 402 (paid tier), we gracefully
|
||||
degrade and return partial data rather than failing entirely, and
|
||||
record the affected field in ``unavailable_fields``.
|
||||
"""
|
||||
try:
|
||||
endpoints_402: set[str] = set()
|
||||
|
||||
async with httpx.AsyncClient(timeout=30.0, verify=_CA_BUNDLE_PATH) as client:
|
||||
params = {"symbol": ticker, "apikey": self._api_key}
|
||||
|
||||
# Profile is the primary source — must succeed
|
||||
profile = await self._fetch_json(client, "profile", params, ticker)
|
||||
|
||||
# Supplementary sources — degrade gracefully on 402
|
||||
ratios, was_402 = await self._fetch_json_optional(client, "ratios-ttm", params, ticker)
|
||||
if was_402:
|
||||
endpoints_402.add("ratios-ttm")
|
||||
|
||||
growth, was_402 = await self._fetch_json_optional(client, "financial-growth", params, ticker)
|
||||
if was_402:
|
||||
endpoints_402.add("financial-growth")
|
||||
|
||||
earnings, was_402 = await self._fetch_json_optional(client, "earnings", params, ticker)
|
||||
if was_402:
|
||||
endpoints_402.add("earnings")
|
||||
|
||||
pe_ratio = self._safe_float(ratios.get("priceToEarningsRatioTTM"))
|
||||
revenue_growth = self._safe_float(growth.get("revenueGrowth"))
|
||||
market_cap = self._safe_float(profile.get("marketCap"))
|
||||
earnings_surprise = self._compute_earnings_surprise(earnings)
|
||||
|
||||
# Build unavailable_fields from 402 endpoints
|
||||
unavailable_fields: dict[str, str] = {
|
||||
self._ENDPOINT_FIELD_MAP[ep]: "requires paid plan"
|
||||
for ep in endpoints_402
|
||||
if ep in self._ENDPOINT_FIELD_MAP
|
||||
}
|
||||
|
||||
return FundamentalData(
|
||||
ticker=ticker,
|
||||
pe_ratio=pe_ratio,
|
||||
revenue_growth=revenue_growth,
|
||||
earnings_surprise=earnings_surprise,
|
||||
market_cap=market_cap,
|
||||
fetched_at=datetime.now(timezone.utc),
|
||||
unavailable_fields=unavailable_fields,
|
||||
)
|
||||
|
||||
except (ProviderError, RateLimitError):
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.error("FMP provider error for %s: %s", ticker, exc)
|
||||
raise ProviderError(f"FMP provider error for {ticker}: {exc}") from exc
|
||||
|
||||
async def _fetch_json(
|
||||
self,
|
||||
client: httpx.AsyncClient,
|
||||
endpoint: str,
|
||||
params: dict,
|
||||
ticker: str,
|
||||
) -> dict:
|
||||
"""Fetch a stable endpoint and return the first item (or empty dict)."""
|
||||
url = f"{_FMP_STABLE_URL}/{endpoint}"
|
||||
resp = await client.get(url, params=params)
|
||||
self._check_response(resp, ticker, endpoint)
|
||||
data = resp.json()
|
||||
if isinstance(data, list):
|
||||
return data[0] if data else {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
async def _fetch_json_optional(
|
||||
self,
|
||||
client: httpx.AsyncClient,
|
||||
endpoint: str,
|
||||
params: dict,
|
||||
ticker: str,
|
||||
) -> tuple[dict, bool]:
|
||||
"""Fetch a stable endpoint, returning ``({}, True)`` on 402 (paid tier).
|
||||
|
||||
Returns a tuple of (data_dict, was_402) so callers can track which
|
||||
endpoints required a paid plan.
|
||||
"""
|
||||
url = f"{_FMP_STABLE_URL}/{endpoint}"
|
||||
resp = await client.get(url, params=params)
|
||||
if resp.status_code == 402:
|
||||
logger.warning("FMP %s requires paid plan — skipping for %s", endpoint, ticker)
|
||||
return {}, True
|
||||
self._check_response(resp, ticker, endpoint)
|
||||
data = resp.json()
|
||||
if isinstance(data, list):
|
||||
return (data[0] if data else {}, False)
|
||||
return (data if isinstance(data, dict) else {}, False)
|
||||
|
||||
def _compute_earnings_surprise(self, earnings_data: dict) -> float | None:
|
||||
"""Compute earnings surprise % from the most recent actual vs estimated EPS."""
|
||||
actual = self._safe_float(earnings_data.get("epsActual"))
|
||||
estimated = self._safe_float(earnings_data.get("epsEstimated"))
|
||||
if actual is None or estimated is None or estimated == 0:
|
||||
return None
|
||||
return ((actual - estimated) / abs(estimated)) * 100
|
||||
|
||||
def _check_response(
|
||||
self, resp: httpx.Response, ticker: str, endpoint: str
|
||||
) -> None:
|
||||
"""Raise appropriate errors for non-200 responses."""
|
||||
if resp.status_code == 429:
|
||||
raise RateLimitError(f"FMP rate limit hit for {ticker} ({endpoint})")
|
||||
if resp.status_code == 403:
|
||||
raise ProviderError(
|
||||
f"FMP {endpoint} access denied for {ticker}: HTTP 403 — check API key validity and plan tier"
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
raise ProviderError(
|
||||
f"FMP {endpoint} error for {ticker}: HTTP {resp.status_code}"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _safe_float(value: object) -> float | None:
|
||||
"""Convert a value to float, returning None on failure."""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
@@ -1,351 +0,0 @@
|
||||
"""Chained fundamentals provider with fallback adapters.
|
||||
|
||||
Order:
|
||||
1) FMP (if configured)
|
||||
2) Finnhub (if configured)
|
||||
3) Alpha Vantage (if configured)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from app.config import settings
|
||||
from app.exceptions import ProviderError, RateLimitError
|
||||
from app.providers.fmp import FMPFundamentalProvider
|
||||
from app.providers.protocol import FundamentalData, FundamentalProvider
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_CA_BUNDLE = os.environ.get("SSL_CERT_FILE", "")
|
||||
if not _CA_BUNDLE or not Path(_CA_BUNDLE).exists():
|
||||
_CA_BUNDLE_PATH: str | bool = True
|
||||
else:
|
||||
_CA_BUNDLE_PATH = _CA_BUNDLE
|
||||
|
||||
|
||||
def _safe_float(value: object) -> float | None:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _to_api_symbol(symbol: str) -> str:
|
||||
"""Convert internal symbol format (BRK-B) to API format (BRK.B).
|
||||
|
||||
Finnhub and Alpha Vantage use dot-separated share class notation.
|
||||
"""
|
||||
return symbol.replace("-", ".")
|
||||
|
||||
|
||||
class FinnhubFundamentalProvider:
|
||||
"""Fundamentals provider backed by Finnhub free endpoints."""
|
||||
|
||||
def __init__(self, api_key: str) -> None:
|
||||
if not api_key:
|
||||
raise ProviderError("Finnhub API key is required")
|
||||
self._api_key = api_key
|
||||
self._base_url = "https://finnhub.io/api/v1"
|
||||
|
||||
async def fetch_fundamentals(self, ticker: str) -> FundamentalData:
|
||||
unavailable: dict[str, str] = {}
|
||||
api_symbol = _to_api_symbol(ticker)
|
||||
|
||||
today = date.today()
|
||||
async with httpx.AsyncClient(timeout=30.0, verify=_CA_BUNDLE_PATH) as client:
|
||||
profile_resp = await client.get(
|
||||
f"{self._base_url}/stock/profile2",
|
||||
params={"symbol": api_symbol, "token": self._api_key},
|
||||
)
|
||||
metric_resp = await client.get(
|
||||
f"{self._base_url}/stock/metric",
|
||||
params={"symbol": api_symbol, "metric": "all", "token": self._api_key},
|
||||
)
|
||||
earnings_resp = await client.get(
|
||||
f"{self._base_url}/stock/earnings",
|
||||
params={"symbol": api_symbol, "limit": 1, "token": self._api_key},
|
||||
)
|
||||
calendar_resp = await client.get(
|
||||
f"{self._base_url}/calendar/earnings",
|
||||
params={
|
||||
"symbol": api_symbol,
|
||||
"from": today.isoformat(),
|
||||
"to": (today + timedelta(days=120)).isoformat(),
|
||||
"token": self._api_key,
|
||||
},
|
||||
)
|
||||
|
||||
for resp, endpoint in (
|
||||
(profile_resp, "profile2"),
|
||||
(metric_resp, "stock/metric"),
|
||||
(earnings_resp, "stock/earnings"),
|
||||
(calendar_resp, "calendar/earnings"),
|
||||
):
|
||||
if resp.status_code == 429:
|
||||
raise RateLimitError(f"Finnhub rate limit hit for {ticker} ({endpoint})")
|
||||
if resp.status_code in (401, 403):
|
||||
raise ProviderError(f"Finnhub access denied for {ticker} ({endpoint}): HTTP {resp.status_code}")
|
||||
if resp.status_code != 200:
|
||||
raise ProviderError(f"Finnhub error for {ticker} ({endpoint}): HTTP {resp.status_code}")
|
||||
|
||||
profile_payload = profile_resp.json() if profile_resp.text else {}
|
||||
metric_payload = metric_resp.json() if metric_resp.text else {}
|
||||
earnings_payload = earnings_resp.json() if earnings_resp.text else []
|
||||
|
||||
metrics = metric_payload.get("metric", {}) if isinstance(metric_payload, dict) else {}
|
||||
market_cap = _safe_float((profile_payload or {}).get("marketCapitalization"))
|
||||
pe_ratio = _safe_float(metrics.get("peTTM") or metrics.get("peNormalizedAnnual"))
|
||||
revenue_growth = _safe_float(metrics.get("revenueGrowthTTMYoy") or metrics.get("revenueGrowth5Y"))
|
||||
|
||||
earnings_surprise = None
|
||||
if isinstance(earnings_payload, list) and earnings_payload:
|
||||
first = earnings_payload[0] if isinstance(earnings_payload[0], dict) else {}
|
||||
earnings_surprise = _safe_float(first.get("surprisePercent"))
|
||||
|
||||
next_earnings_date = self._next_earnings(calendar_resp)
|
||||
|
||||
if pe_ratio is None:
|
||||
unavailable["pe_ratio"] = "not available from provider payload"
|
||||
if revenue_growth is None:
|
||||
unavailable["revenue_growth"] = "not available from provider payload"
|
||||
if earnings_surprise is None:
|
||||
unavailable["earnings_surprise"] = "not available from provider payload"
|
||||
if market_cap is None:
|
||||
unavailable["market_cap"] = "not available from provider payload"
|
||||
|
||||
return FundamentalData(
|
||||
ticker=ticker,
|
||||
pe_ratio=pe_ratio,
|
||||
revenue_growth=revenue_growth,
|
||||
earnings_surprise=earnings_surprise,
|
||||
market_cap=market_cap,
|
||||
fetched_at=datetime.now(timezone.utc),
|
||||
next_earnings_date=next_earnings_date,
|
||||
unavailable_fields=unavailable,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _next_earnings(resp: httpx.Response) -> date | None:
|
||||
"""Earliest upcoming earnings date from Finnhub's calendar payload."""
|
||||
try:
|
||||
payload = resp.json() if resp.text else {}
|
||||
except ValueError:
|
||||
return None
|
||||
entries = payload.get("earningsCalendar", []) if isinstance(payload, dict) else []
|
||||
dates: list[date] = []
|
||||
today = date.today()
|
||||
for entry in entries if isinstance(entries, list) else []:
|
||||
raw = entry.get("date") if isinstance(entry, dict) else None
|
||||
if not raw:
|
||||
continue
|
||||
try:
|
||||
parsed = date.fromisoformat(raw)
|
||||
except ValueError:
|
||||
continue
|
||||
if parsed >= today:
|
||||
dates.append(parsed)
|
||||
return min(dates) if dates else None
|
||||
|
||||
|
||||
class AlphaVantageFundamentalProvider:
|
||||
"""Fundamentals provider backed by Alpha Vantage free endpoints."""
|
||||
|
||||
def __init__(self, api_key: str) -> None:
|
||||
if not api_key:
|
||||
raise ProviderError("Alpha Vantage API key is required")
|
||||
self._api_key = api_key
|
||||
self._base_url = "https://www.alphavantage.co/query"
|
||||
|
||||
async def fetch_fundamentals(self, ticker: str) -> FundamentalData:
|
||||
unavailable: dict[str, str] = {}
|
||||
api_symbol = _to_api_symbol(ticker)
|
||||
|
||||
async with httpx.AsyncClient(timeout=30.0, verify=_CA_BUNDLE_PATH) as client:
|
||||
overview_resp = await client.get(
|
||||
self._base_url,
|
||||
params={"function": "OVERVIEW", "symbol": api_symbol, "apikey": self._api_key},
|
||||
)
|
||||
earnings_resp = await client.get(
|
||||
self._base_url,
|
||||
params={"function": "EARNINGS", "symbol": api_symbol, "apikey": self._api_key},
|
||||
)
|
||||
income_resp = await client.get(
|
||||
self._base_url,
|
||||
params={"function": "INCOME_STATEMENT", "symbol": api_symbol, "apikey": self._api_key},
|
||||
)
|
||||
|
||||
for resp, endpoint in (
|
||||
(overview_resp, "OVERVIEW"),
|
||||
(earnings_resp, "EARNINGS"),
|
||||
(income_resp, "INCOME_STATEMENT"),
|
||||
):
|
||||
if resp.status_code == 429:
|
||||
raise RateLimitError(f"Alpha Vantage rate limit hit for {ticker} ({endpoint})")
|
||||
if resp.status_code != 200:
|
||||
raise ProviderError(f"Alpha Vantage error for {ticker} ({endpoint}): HTTP {resp.status_code}")
|
||||
|
||||
overview = overview_resp.json() if overview_resp.text else {}
|
||||
earnings = earnings_resp.json() if earnings_resp.text else {}
|
||||
income = income_resp.json() if income_resp.text else {}
|
||||
|
||||
if isinstance(overview, dict) and overview.get("Information"):
|
||||
raise ProviderError(f"Alpha Vantage unavailable for {ticker}: {overview.get('Information')}")
|
||||
if isinstance(overview, dict) and overview.get("Note"):
|
||||
raise RateLimitError(f"Alpha Vantage rate limit for {ticker}: {overview.get('Note')}")
|
||||
|
||||
pe_ratio = _safe_float((overview or {}).get("PERatio"))
|
||||
market_cap = _safe_float((overview or {}).get("MarketCapitalization"))
|
||||
|
||||
earnings_surprise = None
|
||||
quarterly = earnings.get("quarterlyEarnings", []) if isinstance(earnings, dict) else []
|
||||
if isinstance(quarterly, list) and quarterly:
|
||||
first = quarterly[0] if isinstance(quarterly[0], dict) else {}
|
||||
earnings_surprise = _safe_float(first.get("surprisePercentage"))
|
||||
|
||||
revenue_growth = None
|
||||
annual = income.get("annualReports", []) if isinstance(income, dict) else []
|
||||
if isinstance(annual, list) and len(annual) >= 2:
|
||||
curr = _safe_float((annual[0] or {}).get("totalRevenue"))
|
||||
prev = _safe_float((annual[1] or {}).get("totalRevenue"))
|
||||
if curr is not None and prev not in (None, 0):
|
||||
revenue_growth = ((curr - prev) / abs(prev)) * 100.0
|
||||
|
||||
if pe_ratio is None:
|
||||
unavailable["pe_ratio"] = "not available from provider payload"
|
||||
if revenue_growth is None:
|
||||
unavailable["revenue_growth"] = "not available from provider payload"
|
||||
if earnings_surprise is None:
|
||||
unavailable["earnings_surprise"] = "not available from provider payload"
|
||||
if market_cap is None:
|
||||
unavailable["market_cap"] = "not available from provider payload"
|
||||
|
||||
return FundamentalData(
|
||||
ticker=ticker,
|
||||
pe_ratio=pe_ratio,
|
||||
revenue_growth=revenue_growth,
|
||||
earnings_surprise=earnings_surprise,
|
||||
market_cap=market_cap,
|
||||
fetched_at=datetime.now(timezone.utc),
|
||||
unavailable_fields=unavailable,
|
||||
)
|
||||
|
||||
|
||||
_FUNDAMENTAL_FIELDS = ("pe_ratio", "revenue_growth", "earnings_surprise", "market_cap")
|
||||
|
||||
|
||||
class ChainedFundamentalProvider:
|
||||
"""Merge fundamentals across providers, filling gaps from later sources.
|
||||
|
||||
A single provider rarely covers everything on free tiers — FMP's free plan,
|
||||
for example, returns only market cap (the ratios/growth/earnings endpoints
|
||||
402). Rather than stop at the first provider with *any* field, we take each
|
||||
field from the first provider that supplies it, so FMP's market cap is
|
||||
combined with Finnhub's P/E and earnings surprise.
|
||||
"""
|
||||
|
||||
def __init__(self, providers: list[tuple[str, FundamentalProvider]]) -> None:
|
||||
if not providers:
|
||||
raise ProviderError("No fundamental providers configured")
|
||||
self._providers = providers
|
||||
|
||||
async def fetch_fundamentals(self, ticker: str, allow_partial: bool = False) -> FundamentalData:
|
||||
"""Merge fundamentals across providers.
|
||||
|
||||
``allow_partial`` controls behaviour when a fallback provider is *rate
|
||||
limited* and we end up with missing fields. By default we raise
|
||||
RateLimitError so the caller (the bulk collector) can back off and retry
|
||||
the ticker once the window frees — otherwise a transient 429 on Finnhub
|
||||
would be silently stored as market-cap-only. Pass ``allow_partial=True``
|
||||
(manual single fetches, or the collector's final give-up attempt) to
|
||||
accept whatever was gathered instead of raising.
|
||||
"""
|
||||
merged: dict[str, float | None] = {f: None for f in _FUNDAMENTAL_FIELDS}
|
||||
field_source: dict[str, str] = {}
|
||||
errors: list[str] = []
|
||||
rate_limited = False
|
||||
next_earnings_date = None
|
||||
|
||||
for provider_name, provider in self._providers:
|
||||
if all(merged[f] is not None for f in _FUNDAMENTAL_FIELDS) and next_earnings_date:
|
||||
break
|
||||
try:
|
||||
data = await provider.fetch_fundamentals(ticker)
|
||||
except RateLimitError as exc:
|
||||
rate_limited = True
|
||||
errors.append(f"{provider_name}: RateLimitError: {exc}")
|
||||
continue
|
||||
except Exception as exc:
|
||||
errors.append(f"{provider_name}: {type(exc).__name__}: {exc}")
|
||||
continue
|
||||
|
||||
if next_earnings_date is None and data.next_earnings_date is not None:
|
||||
next_earnings_date = data.next_earnings_date
|
||||
|
||||
for field in _FUNDAMENTAL_FIELDS:
|
||||
if merged[field] is None:
|
||||
value = getattr(data, field)
|
||||
if value is not None:
|
||||
merged[field] = value
|
||||
field_source[field] = provider_name
|
||||
|
||||
missing = [f for f in _FUNDAMENTAL_FIELDS if merged[f] is None]
|
||||
|
||||
# A rate limit left data incomplete: signal it (unless partial is OK) so
|
||||
# the collector backs off rather than persisting a degraded record.
|
||||
if rate_limited and missing and not allow_partial:
|
||||
attempts = "; ".join(errors[:6])
|
||||
raise RateLimitError(
|
||||
f"Fundamentals incomplete for {ticker} due to provider rate limits "
|
||||
f"(missing {', '.join(missing)}). Attempts: {attempts}"
|
||||
)
|
||||
|
||||
if all(merged[f] is None for f in _FUNDAMENTAL_FIELDS):
|
||||
attempts = "; ".join(errors[:6]) if errors else "no usable metrics from any provider"
|
||||
raise ProviderError(f"All fundamentals providers failed for {ticker}. Attempts: {attempts}")
|
||||
|
||||
unavailable: dict[str, str] = {
|
||||
field: "not available from any configured provider"
|
||||
for field in _FUNDAMENTAL_FIELDS
|
||||
if merged[field] is None
|
||||
}
|
||||
# Record which provider supplied each field for transparency.
|
||||
for field, src in field_source.items():
|
||||
unavailable[f"source_{field}"] = src
|
||||
|
||||
return FundamentalData(
|
||||
ticker=ticker,
|
||||
pe_ratio=merged["pe_ratio"],
|
||||
revenue_growth=merged["revenue_growth"],
|
||||
earnings_surprise=merged["earnings_surprise"],
|
||||
market_cap=merged["market_cap"],
|
||||
fetched_at=datetime.now(timezone.utc),
|
||||
next_earnings_date=next_earnings_date,
|
||||
unavailable_fields=unavailable,
|
||||
)
|
||||
|
||||
|
||||
def build_fundamental_provider_chain() -> FundamentalProvider:
|
||||
providers: list[tuple[str, FundamentalProvider]] = []
|
||||
|
||||
if settings.fmp_api_key:
|
||||
providers.append(("fmp", FMPFundamentalProvider(settings.fmp_api_key)))
|
||||
if settings.finnhub_api_key:
|
||||
providers.append(("finnhub", FinnhubFundamentalProvider(settings.finnhub_api_key)))
|
||||
if settings.alpha_vantage_api_key:
|
||||
providers.append(("alpha_vantage", AlphaVantageFundamentalProvider(settings.alpha_vantage_api_key)))
|
||||
|
||||
if not providers:
|
||||
raise ProviderError(
|
||||
"No fundamentals provider configured. Set one of FMP_API_KEY, FINNHUB_API_KEY, ALPHA_VANTAGE_API_KEY"
|
||||
)
|
||||
|
||||
logger.info("Fundamentals provider chain configured: %s", [name for name, _ in providers])
|
||||
return ChainedFundamentalProvider(providers)
|
||||
@@ -44,20 +44,6 @@ class SentimentData:
|
||||
recommendation: str | None = None # "buy" | "hold" | "avoid" — actionable LLM view
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FundamentalData:
|
||||
"""Fundamental metrics returned by fundamental providers."""
|
||||
|
||||
ticker: str
|
||||
pe_ratio: float | None
|
||||
revenue_growth: float | None
|
||||
earnings_surprise: float | None
|
||||
market_cap: float | None
|
||||
fetched_at: datetime
|
||||
next_earnings_date: date | None = None
|
||||
unavailable_fields: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Provider Protocols
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -81,9 +67,5 @@ class SentimentProvider(Protocol):
|
||||
...
|
||||
|
||||
|
||||
class FundamentalProvider(Protocol):
|
||||
"""Protocol for fundamental data providers."""
|
||||
|
||||
async def fetch_fundamentals(self, ticker: str) -> FundamentalData:
|
||||
"""Fetch fundamental data for a ticker."""
|
||||
...
|
||||
# No fundamentals provider protocol: since A6 fundamentals come only from the
|
||||
# batch SEC/Dolt imports, never from a request-time provider call.
|
||||
|
||||
+104
-3
@@ -6,17 +6,20 @@ All endpoints require admin role.
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.dependencies import get_db, require_admin
|
||||
from app.dependencies import get_db, require_access, require_admin
|
||||
from app.models.user import User
|
||||
from app.schemas.admin import (
|
||||
ActivationConfigUpdate,
|
||||
AlertConfigUpdate,
|
||||
CreateUserRequest,
|
||||
DataCleanupRequest,
|
||||
JobTriggerRequest,
|
||||
JobToggle,
|
||||
RecommendationConfigUpdate,
|
||||
PerformanceConfigUpdate,
|
||||
ScheduleConfigUpdate,
|
||||
SentimentConfigUpdate,
|
||||
ShadowBookConfigUpdate,
|
||||
SentimentTestRequest,
|
||||
PasswordReset,
|
||||
RegistrationToggle,
|
||||
@@ -28,6 +31,7 @@ from app.schemas.common import APIEnvelope
|
||||
from app.services import admin_service
|
||||
from app.services import alert_service
|
||||
from app.services import sentiment_provider_service
|
||||
from app.services import system_event_service
|
||||
from app.services import ticker_universe_service
|
||||
|
||||
router = APIRouter(tags=["admin"])
|
||||
@@ -199,6 +203,50 @@ async def update_schedule_settings(
|
||||
return APIEnvelope(status="success", data=updated)
|
||||
|
||||
|
||||
@router.get("/admin/settings/performance", response_model=APIEnvelope)
|
||||
async def get_performance_settings(
|
||||
_admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return APIEnvelope(
|
||||
status="success", data=await admin_service.get_performance_config(db)
|
||||
)
|
||||
|
||||
|
||||
@router.put("/admin/settings/performance", response_model=APIEnvelope)
|
||||
async def update_performance_settings(
|
||||
body: PerformanceConfigUpdate,
|
||||
_admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
updated = await admin_service.update_performance_config(
|
||||
db, body.model_dump(exclude_unset=True)
|
||||
)
|
||||
return APIEnvelope(status="success", data=updated)
|
||||
|
||||
|
||||
@router.get("/admin/settings/shadow-book", response_model=APIEnvelope)
|
||||
async def get_shadow_book_settings(
|
||||
_admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return APIEnvelope(
|
||||
status="success", data=await admin_service.get_shadow_book_config(db)
|
||||
)
|
||||
|
||||
|
||||
@router.put("/admin/settings/shadow-book", response_model=APIEnvelope)
|
||||
async def update_shadow_book_settings(
|
||||
body: ShadowBookConfigUpdate,
|
||||
_admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
updated = await admin_service.update_shadow_book_config(
|
||||
db, body.model_dump(exclude_unset=True, exclude_none=True)
|
||||
)
|
||||
return APIEnvelope(status="success", data=updated)
|
||||
|
||||
|
||||
@router.get("/admin/settings/sentiment", response_model=APIEnvelope)
|
||||
async def get_sentiment_settings(
|
||||
_admin: User = Depends(require_admin),
|
||||
@@ -376,11 +424,17 @@ async def get_pipeline_readiness(
|
||||
@router.post("/admin/jobs/{job_name}/trigger", response_model=APIEnvelope)
|
||||
async def trigger_job(
|
||||
job_name: str,
|
||||
body: JobTriggerRequest | None = None,
|
||||
_admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Trigger a manual job run (placeholder)."""
|
||||
result = await admin_service.trigger_job(db, job_name)
|
||||
"""Trigger a manual job run, optionally with one-run parameters."""
|
||||
result = await admin_service.trigger_job(
|
||||
db,
|
||||
job_name,
|
||||
target_model=body.target_model if body is not None else None,
|
||||
cadence=body.cadence if body is not None else None,
|
||||
)
|
||||
return APIEnvelope(status="success", data=result)
|
||||
|
||||
|
||||
@@ -397,3 +451,50 @@ async def toggle_job(
|
||||
status="success",
|
||||
data={"key": setting.key, "value": setting.value},
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# System events (operational warnings / errors)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.get("/admin/system-events", response_model=APIEnvelope)
|
||||
async def list_system_events(
|
||||
days: int = Query(7, ge=1, le=30),
|
||||
severity: str | None = Query(None, description="warning | error"),
|
||||
unacknowledged_only: bool = Query(False),
|
||||
_user: User = Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""List recent system events (default last 7 days)."""
|
||||
rows = await system_event_service.list_events(
|
||||
db,
|
||||
days=days,
|
||||
severity=severity,
|
||||
unacknowledged_only=unacknowledged_only,
|
||||
)
|
||||
return APIEnvelope(
|
||||
status="success",
|
||||
data=[system_event_service.event_to_dict(r) for r in rows],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/admin/system-events/summary", response_model=APIEnvelope)
|
||||
async def system_events_summary(
|
||||
days: int = Query(7, ge=1, le=30),
|
||||
_user: User = Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Badge counts for the top nav."""
|
||||
data = await system_event_service.summary(db, days=days)
|
||||
return APIEnvelope(status="success", data=data)
|
||||
|
||||
|
||||
@router.post("/admin/system-events/acknowledge", response_model=APIEnvelope)
|
||||
async def acknowledge_system_events(
|
||||
days: int = Query(7, ge=1, le=30),
|
||||
_user: User = Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Dismiss unacknowledged events in the lookback window (clears the badge)."""
|
||||
count = await system_event_service.acknowledge_all(db, days=days)
|
||||
return APIEnvelope(status="success", data={"acknowledged": count})
|
||||
|
||||
@@ -9,6 +9,8 @@ from app.dependencies import get_db, require_access
|
||||
from app.schemas.common import APIEnvelope
|
||||
from app.schemas.fundamental import FundamentalResponse
|
||||
from app.services.fundamental_service import get_fundamental
|
||||
from app.services.fundamentals_api_service import build_fundamentals_v1
|
||||
from app.services import fundamentals_quality_service
|
||||
|
||||
router = APIRouter(tags=["fundamentals"])
|
||||
|
||||
@@ -30,14 +32,14 @@ async def read_fundamentals(
|
||||
_user=Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> APIEnvelope:
|
||||
"""Get latest fundamental data for a symbol."""
|
||||
"""Get latest fundamental data for a symbol (legacy fields + additive v1)."""
|
||||
record = await get_fundamental(db, symbol)
|
||||
v1 = await build_fundamentals_v1(db, symbol)
|
||||
quality = await fundamentals_quality_service.ticker_quality(db, symbol)
|
||||
|
||||
if record is None:
|
||||
data = FundamentalResponse(symbol=symbol.strip().upper())
|
||||
else:
|
||||
data = FundamentalResponse(
|
||||
symbol=symbol.strip().upper(),
|
||||
legacy: dict = {}
|
||||
if record is not None:
|
||||
legacy = dict(
|
||||
pe_ratio=record.pe_ratio,
|
||||
revenue_growth=record.revenue_growth,
|
||||
earnings_surprise=record.earnings_surprise,
|
||||
@@ -47,4 +49,12 @@ async def read_fundamentals(
|
||||
unavailable_fields=_parse_unavailable_fields(record.unavailable_fields_json),
|
||||
)
|
||||
|
||||
data = FundamentalResponse(
|
||||
symbol=symbol.strip().upper(),
|
||||
setup_eligible=quality.eligible,
|
||||
setup_block_code=quality.code,
|
||||
setup_block_reason=quality.message,
|
||||
**legacy,
|
||||
**v1,
|
||||
)
|
||||
return APIEnvelope(status="success", data=data.model_dump())
|
||||
|
||||
+47
-32
@@ -19,15 +19,17 @@ from app.dependencies import get_db, require_access
|
||||
from app.exceptions import ProviderError
|
||||
from app.models.ohlcv import OHLCVRecord
|
||||
from app.models.settings import IngestionProgress
|
||||
from app.models.sr_level import SRLevel
|
||||
from app.models.ticker import Ticker
|
||||
from app.models.user import User
|
||||
from app.providers.alpaca import AlpacaOHLCVProvider
|
||||
from app.providers.fundamentals_chain import build_fundamental_provider_chain
|
||||
from app.services.rr_scanner_service import scan_ticker
|
||||
from app.services.rr_scanner_service import (
|
||||
resolve_activation_ranks_for_symbol,
|
||||
scan_ticker,
|
||||
)
|
||||
from app.services.sentiment_provider_service import build_sentiment_provider
|
||||
from app.schemas.common import APIEnvelope
|
||||
from app.services import (
|
||||
fundamental_service,
|
||||
ingestion_service,
|
||||
scoring_service,
|
||||
sentiment_service,
|
||||
@@ -102,8 +104,13 @@ async def fetch_symbol(
|
||||
await db.execute(
|
||||
delete(IngestionProgress).where(IngestionProgress.ticker_id == ticker_obj.id)
|
||||
)
|
||||
# Drop Structural S/R with the bars; a failed re-fetch must not
|
||||
# leave zones computed from deleted history.
|
||||
await db.execute(
|
||||
delete(SRLevel).where(SRLevel.ticker_id == ticker_obj.id)
|
||||
)
|
||||
await db.commit()
|
||||
logger.info("force_refetch: cleared OHLCV and progress for %s", symbol_upper)
|
||||
logger.info("force_refetch: cleared OHLCV, S/R, and progress for %s", symbol_upper)
|
||||
except Exception as exc:
|
||||
logger.error("force_refetch cleanup failed for %s: %s", symbol_upper, exc)
|
||||
|
||||
@@ -114,12 +121,32 @@ async def fetch_symbol(
|
||||
result = await ingestion_service.fetch_and_ingest(
|
||||
db, provider, symbol_upper, start_date, end_date
|
||||
)
|
||||
status_map = {"complete": "ok", "partial": "ok", "no_data": "warning"}
|
||||
# "stale" = provider returned nothing but our last bar is old
|
||||
# (rename/delist/halt) — must not look like a successful refresh.
|
||||
status_map = {
|
||||
"complete": "ok",
|
||||
"partial": "ok",
|
||||
"no_data": "warning",
|
||||
"stale": "warning",
|
||||
}
|
||||
sources_out["ohlcv"] = {
|
||||
"status": status_map.get(result.status, "error"),
|
||||
"records": result.records_ingested,
|
||||
"message": result.message,
|
||||
"last_date": result.last_date.isoformat() if result.last_date else None,
|
||||
}
|
||||
if result.status in ("stale", "no_data", "error"):
|
||||
from app.services.system_event_service import log_event
|
||||
|
||||
await log_event(
|
||||
db,
|
||||
severity="warning" if result.status != "error" else "error",
|
||||
source="ingestion",
|
||||
code=f"ohlcv_{result.status}",
|
||||
message=result.message or f"OHLCV fetch {result.status} for {symbol_upper}",
|
||||
symbol=symbol_upper,
|
||||
dedup_key=f"ohlcv_{result.status}:{symbol_upper}",
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("OHLCV fetch failed for %s: %s", symbol_upper, exc)
|
||||
sources_out["ohlcv"] = {"status": "error", "records": 0, "message": str(exc)}
|
||||
@@ -156,34 +183,14 @@ async def fetch_symbol(
|
||||
sources_out["sentiment"] = {"status": "error", "message": str(exc)}
|
||||
|
||||
# --- Fundamentals ---
|
||||
# No per-ticker fetch exists any more: fundamental_data is rebuilt for the
|
||||
# whole universe by the nightly SEC + Dolt imports, from local PostgreSQL.
|
||||
# The source key is still accepted so older clients get a truthful answer.
|
||||
if "fundamentals" in requested:
|
||||
if settings.fmp_api_key or settings.finnhub_api_key or settings.alpha_vantage_api_key:
|
||||
try:
|
||||
fundamentals_provider = build_fundamental_provider_chain()
|
||||
# Manual single fetch: take whatever we can get (a lone 429 on a
|
||||
# fallback shouldn't fail the whole refresh).
|
||||
fdata = await fundamentals_provider.fetch_fundamentals(
|
||||
symbol_upper, allow_partial=True
|
||||
)
|
||||
await fundamental_service.store_fundamental(
|
||||
db,
|
||||
symbol=symbol_upper,
|
||||
pe_ratio=fdata.pe_ratio,
|
||||
revenue_growth=fdata.revenue_growth,
|
||||
earnings_surprise=fdata.earnings_surprise,
|
||||
market_cap=fdata.market_cap,
|
||||
next_earnings_date=fdata.next_earnings_date,
|
||||
unavailable_fields=fdata.unavailable_fields,
|
||||
)
|
||||
sources_out["fundamentals"] = {"status": "ok", "message": None}
|
||||
except Exception as exc:
|
||||
logger.error("Fundamentals fetch failed for %s: %s", symbol_upper, exc)
|
||||
sources_out["fundamentals"] = {"status": "error", "message": str(exc)}
|
||||
else:
|
||||
sources_out["fundamentals"] = {
|
||||
"status": "skipped",
|
||||
"message": "No fundamentals provider key configured",
|
||||
}
|
||||
sources_out["fundamentals"] = {
|
||||
"status": "skipped",
|
||||
"message": "Fundamentals refresh nightly from the SEC + Dolt imports",
|
||||
}
|
||||
|
||||
# --- Derived pipeline: S/R levels (free, always) ---
|
||||
try:
|
||||
@@ -216,15 +223,23 @@ async def fetch_symbol(
|
||||
sources_out["scores"] = {"status": "error", "message": str(exc)}
|
||||
|
||||
# --- Derived pipeline: scanner (free, always) ---
|
||||
# Attach the same residual-momentum / strategy ranks the daily scan writes.
|
||||
# Without them the new setup lands with null momentum_percentile and fails
|
||||
# the activation gate (missing ranks do not qualify).
|
||||
try:
|
||||
ranks = await resolve_activation_ranks_for_symbol(db, symbol_upper)
|
||||
setups = await scan_ticker(
|
||||
db,
|
||||
symbol_upper,
|
||||
rr_threshold=settings.default_rr_threshold,
|
||||
momentum_percentile=ranks.get("momentum_percentile"),
|
||||
strategy_rank=ranks.get("strategy_rank"),
|
||||
volatility_percentile=ranks.get("volatility_percentile"),
|
||||
)
|
||||
sources_out["scanner"] = {
|
||||
"status": "ok",
|
||||
"setups_found": len(setups),
|
||||
"momentum_percentile": ranks.get("momentum_percentile"),
|
||||
"message": None,
|
||||
}
|
||||
except Exception as exc:
|
||||
|
||||
+31
-17
@@ -1,7 +1,9 @@
|
||||
"""Market-level endpoints (benchmark regime + AI/Tech regime-change monitor)."""
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.dependencies import get_db, require_access, require_admin
|
||||
@@ -40,17 +42,25 @@ async def backtest_report(
|
||||
|
||||
|
||||
class RegimeConfigUpdate(BaseModel):
|
||||
weights: dict[str, float] | None = None
|
||||
alert_threshold: float | None = None
|
||||
tickers: dict | None = None
|
||||
leader_weight: float | None = None
|
||||
rs_lookback: int | None = None
|
||||
fundamental_staleness_days: int | None = None
|
||||
breadth_basket: list[str] | None = Field(default=None, min_length=20, max_length=100)
|
||||
fundamental_staleness_days: int | None = Field(default=None, ge=30, le=180)
|
||||
|
||||
@field_validator("breadth_basket")
|
||||
@classmethod
|
||||
def normalise_basket(cls, value: list[str] | None) -> list[str] | None:
|
||||
if value is None:
|
||||
return None
|
||||
cleaned = [symbol.strip().upper().replace(".", "-") for symbol in value if symbol.strip()]
|
||||
if len(cleaned) != len(set(cleaned)):
|
||||
raise ValueError("breadth basket symbols must be unique")
|
||||
return cleaned
|
||||
|
||||
|
||||
class RegimeFundamentalsUpdate(BaseModel):
|
||||
f1_score: float | None = None
|
||||
f3_score: float | None = None
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
capex: dict[str, Literal["raising", "holding", "cutting", "unknown"]] | None = None
|
||||
good_news_stock_down: Literal["yes", "no", "mixed"] | None = None
|
||||
locked: bool | None = None
|
||||
|
||||
|
||||
@@ -59,7 +69,7 @@ async def regime_monitor(
|
||||
_user: User = Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> APIEnvelope:
|
||||
"""Latest AI/Tech regime-change index (0-100) + per-signal breakdown + trend."""
|
||||
"""Latest v2 State and Warning risk-thermometer readings."""
|
||||
data = await regime_monitor_service.get_regime_monitor(db)
|
||||
return APIEnvelope(status="success", data=data)
|
||||
|
||||
@@ -69,7 +79,7 @@ async def regime_config(
|
||||
_admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> APIEnvelope:
|
||||
"""Editable weights / thresholds / ticker lists for the regime monitor."""
|
||||
"""Editable fixed breadth basket and fundamental freshness window."""
|
||||
data = await regime_monitor_service.get_regime_config(db)
|
||||
return APIEnvelope(status="success", data=data)
|
||||
|
||||
@@ -80,7 +90,7 @@ async def update_regime_config(
|
||||
_admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> APIEnvelope:
|
||||
"""Merge the supplied fields into the stored regime-monitor config."""
|
||||
"""Update the deliberately small v2 operator configuration."""
|
||||
updates = body.model_dump(exclude_none=True)
|
||||
data = await regime_monitor_service.update_regime_config(db, updates)
|
||||
return APIEnvelope(status="success", data=data)
|
||||
@@ -102,9 +112,12 @@ async def update_regime_fundamentals(
|
||||
_admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> APIEnvelope:
|
||||
"""Manually override F1/F3 (locks out the LLM refresh until unlocked)."""
|
||||
"""Manually override categorical F1/F3 observations."""
|
||||
data = await regime_monitor_service.set_fundamental_overrides(
|
||||
db, f1_score=body.f1_score, f3_score=body.f3_score, locked=body.locked
|
||||
db,
|
||||
capex=body.capex,
|
||||
good_news_stock_down=body.good_news_stock_down,
|
||||
locked=body.locked,
|
||||
)
|
||||
return APIEnvelope(status="success", data=data)
|
||||
|
||||
@@ -114,8 +127,9 @@ async def refresh_regime_fundamentals(
|
||||
_admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> APIEnvelope:
|
||||
"""Ask the configured LLM to re-estimate F1/F3 now (forces past a lock)."""
|
||||
"""Refresh F1/F3 via LLM, then recompute the latest eligible snapshot."""
|
||||
data = await regime_monitor_service.refresh_fundamental_overrides(db, force=True)
|
||||
await regime_monitor_service.update_regime_monitor(db)
|
||||
return APIEnvelope(status="success", data=data)
|
||||
|
||||
|
||||
@@ -133,10 +147,10 @@ async def regime_event_study(
|
||||
|
||||
@router.get("/regime/history", response_model=APIEnvelope)
|
||||
async def regime_history(
|
||||
days: int = Query(default=400, ge=7, le=2000),
|
||||
days: int = Query(default=800, ge=7, le=2000),
|
||||
_user: User = Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> APIEnvelope:
|
||||
"""Daily history of the index / early-warning / combined scores (for the chart)."""
|
||||
"""Point-in-time v2 State/Warning history. Legacy rows are excluded."""
|
||||
data = await regime_monitor_service.get_regime_history(db, days=days)
|
||||
return APIEnvelope(status="success", data=data)
|
||||
|
||||
@@ -65,6 +65,18 @@ async def paper_trade_equity_curve(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/paper-trades/performance", response_model=APIEnvelope)
|
||||
async def paper_trade_performance(
|
||||
user: User = Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> APIEnvelope:
|
||||
"""Shadow book vs discretionary book vs SPY since the configured start date."""
|
||||
return APIEnvelope(
|
||||
status="success",
|
||||
data=await paper_trade_service.performance_summary(db, user.id),
|
||||
)
|
||||
|
||||
|
||||
@router.put("/paper-trades/exit-policy", response_model=APIEnvelope)
|
||||
async def write_exit_policy(
|
||||
body: ExitPolicyUpdate,
|
||||
|
||||
@@ -5,17 +5,81 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.dependencies import get_db, require_access
|
||||
from app.schemas.common import APIEnvelope
|
||||
from app.schemas.sr_level import SRLevelResponse, SRLevelResult, SRZoneResult
|
||||
from app.schemas.sr_level import (
|
||||
GateTargetLadderResponse,
|
||||
GateTargetLevelResult,
|
||||
SRLevelResponse,
|
||||
SRLevelResult,
|
||||
SRZoneResult,
|
||||
)
|
||||
from app.services.price_service import query_ohlcv
|
||||
from app.services.sr_service import cluster_sr_zones, get_sr_levels
|
||||
from app.services.sr_service import (
|
||||
cluster_sr_zones,
|
||||
detect_gate_target_ladder,
|
||||
get_sr_levels,
|
||||
)
|
||||
|
||||
router = APIRouter(tags=["sr-levels"])
|
||||
|
||||
|
||||
@router.get("/gate-target-ladder/{symbol}", response_model=APIEnvelope)
|
||||
async def read_gate_target_ladder(
|
||||
symbol: str,
|
||||
_user=Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> APIEnvelope:
|
||||
"""Return the transient, volume-free GTL for chart diagnostics.
|
||||
|
||||
These proposals are not persisted ``SRLevel`` rows and must not be
|
||||
presented as structural support/resistance.
|
||||
"""
|
||||
records = await query_ohlcv(db, symbol)
|
||||
if not records:
|
||||
data = GateTargetLadderResponse(
|
||||
symbol=symbol.upper(),
|
||||
levels=[],
|
||||
count=0,
|
||||
lookback_bars=0,
|
||||
)
|
||||
return APIEnvelope(status="success", data=data.model_dump())
|
||||
|
||||
highs = [float(record.high) for record in records]
|
||||
lows = [float(record.low) for record in records]
|
||||
closes = [float(record.close) for record in records]
|
||||
detected = detect_gate_target_ladder(highs, lows, closes)
|
||||
levels = [
|
||||
GateTargetLevelResult(
|
||||
price_level=float(level["price_level"]),
|
||||
type=level["type"],
|
||||
strength=int(level["strength"]),
|
||||
detection_method=str(level.get("detection_method", "unknown")),
|
||||
sources=list(level.get("sources") or []),
|
||||
traffic_count=int(level.get("rejection_count", 0) or 0),
|
||||
)
|
||||
for level in sorted(detected, key=lambda row: float(row["price_level"]))
|
||||
]
|
||||
data = GateTargetLadderResponse(
|
||||
symbol=symbol.upper(),
|
||||
levels=levels,
|
||||
count=len(levels),
|
||||
lookback_bars=len(records),
|
||||
)
|
||||
return APIEnvelope(status="success", data=data.model_dump())
|
||||
|
||||
|
||||
@router.get("/sr-levels/{symbol}", response_model=APIEnvelope)
|
||||
async def read_sr_levels(
|
||||
symbol: str,
|
||||
tolerance: float = Query(0.005, ge=0, le=0.1, description="Merge tolerance (default 0.5%)"),
|
||||
tolerance: float | None = Query(
|
||||
None,
|
||||
ge=0,
|
||||
le=0.1,
|
||||
description=(
|
||||
"Merge tolerance as fraction of price. Omit to return persisted levels "
|
||||
"(ATR-adaptive at last recalculation). When set, returns a transient "
|
||||
"detect with this tolerance (not written to the DB)."
|
||||
),
|
||||
),
|
||||
max_zones: int = Query(6, ge=0, description="Max S/R zones to return (default 6)"),
|
||||
_user=Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
|
||||
+33
-1
@@ -6,7 +6,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.dependencies import get_db, require_access
|
||||
from app.models.user import User
|
||||
from app.schemas.common import APIEnvelope
|
||||
from app.schemas.ticker import TickerCreate, TickerResponse
|
||||
from app.schemas.ticker import TickerCreate, TickerDelistingUpdate, TickerResponse
|
||||
from app.services import ticker_service
|
||||
|
||||
router = APIRouter(tags=["tickers"])
|
||||
@@ -51,3 +51,35 @@ async def delete_ticker(
|
||||
"""Delete a ticker and all associated data."""
|
||||
await ticker_service.delete_ticker(db, symbol)
|
||||
return APIEnvelope(status="success", data=None)
|
||||
|
||||
|
||||
@router.post("/tickers/{symbol}/delisting", response_model=APIEnvelope)
|
||||
async def mark_ticker_delisted(
|
||||
symbol: str,
|
||||
body: TickerDelistingUpdate,
|
||||
_user: User = Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Retire a symbol: excluded from signals, price history kept.
|
||||
|
||||
The non-destructive alternative to DELETE, which cascades the history away.
|
||||
"""
|
||||
changed = await ticker_service.mark_delisted(
|
||||
db, symbol, delisted_on=body.delisted_on, reason=ticker_service.REASON_MANUAL
|
||||
)
|
||||
return APIEnvelope(status="success", data={"changed": changed})
|
||||
|
||||
|
||||
@router.delete("/tickers/{symbol}/delisting", response_model=APIEnvelope)
|
||||
async def clear_ticker_delisting(
|
||||
symbol: str,
|
||||
_user: User = Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Un-retire a symbol wrongly marked delisted.
|
||||
|
||||
Automatic marking is only defensible because this exists: a false positive
|
||||
costs one row update rather than the price history a delete would take.
|
||||
"""
|
||||
changed = await ticker_service.clear_delisted(db, symbol)
|
||||
return APIEnvelope(status="success", data={"changed": changed})
|
||||
|
||||
+10
-7
@@ -25,7 +25,7 @@ async def list_trade_setups(
|
||||
None,
|
||||
description="Filter by action: LONG_HIGH, LONG_MODERATE, SHORT_HIGH, SHORT_MODERATE, NEUTRAL",
|
||||
),
|
||||
_user=Depends(require_access),
|
||||
user=Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> APIEnvelope:
|
||||
"""Get latest trade setups with recommendation data."""
|
||||
@@ -36,6 +36,8 @@ async def list_trade_setups(
|
||||
recommended_action=recommended_action,
|
||||
live_recommendation=True,
|
||||
exclude_open_trade_tickers=True,
|
||||
exclude_open_trade_user_id=user.id,
|
||||
exclude_reentry_gate_locked_tickers=True,
|
||||
)
|
||||
|
||||
data = []
|
||||
@@ -75,13 +77,13 @@ async def get_trade_performance(
|
||||
_user=Depends(require_access),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> APIEnvelope:
|
||||
"""Aggregate outcome statistics over evaluated trade setups.
|
||||
"""Aggregate setup-outcome statistics (gate barrier diagnostic).
|
||||
|
||||
Outcomes are written by the nightly outcome_evaluator job (win = target
|
||||
hit first, loss = stop hit first, expired = neither within the window).
|
||||
With qualified_only, the overall/direction/action breakdowns cover only
|
||||
setups clearing the activation gate; the confidence breakdown always
|
||||
covers all setups so the gate can be validated against it.
|
||||
Outcomes come from the nightly outcome_evaluator: win = gate target first,
|
||||
loss = stop first, expired = neither in the window. This is **not** the
|
||||
production ATR-trail book; it checks setup grading plumbing only.
|
||||
With qualified_only, overall/direction/action cover only gate-clearing
|
||||
setups; the confidence breakdown always covers all setups.
|
||||
"""
|
||||
config = await admin_service.get_activation_config(db) if qualified_only else None
|
||||
stats = await get_performance_stats(db, config=config)
|
||||
@@ -98,6 +100,7 @@ async def get_ticker_trade_setups(
|
||||
db,
|
||||
symbol=symbol,
|
||||
live_recommendation=True,
|
||||
include_reentry_gate_lock=True,
|
||||
)
|
||||
data = []
|
||||
for row in rows:
|
||||
|
||||
+722
-209
File diff suppressed because it is too large
Load Diff
+32
-2
@@ -43,6 +43,12 @@ class JobToggle(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
|
||||
class JobTriggerRequest(BaseModel):
|
||||
"""Optional parameters for a one-time manual job run."""
|
||||
target_model: Literal["production_gtl", "structural_sr"] | None = None
|
||||
cadence: Literal["weekly", "daily"] | None = None
|
||||
|
||||
|
||||
class RecommendationConfigUpdate(BaseModel):
|
||||
high_confidence_threshold: float | None = Field(default=None, ge=0, le=100)
|
||||
moderate_confidence_threshold: float | None = Field(default=None, ge=0, le=100)
|
||||
@@ -69,11 +75,35 @@ class ActivationConfigUpdate(BaseModel):
|
||||
|
||||
class ScheduleConfigUpdate(BaseModel):
|
||||
"""Cron schedule for the pipelines + fundamentals. Crons are 5-field
|
||||
(min hour dom month dow); timezone is an IANA name (e.g. Europe/Berlin)."""
|
||||
(min hour dom month dow); timezone is an IANA name (e.g. America/New_York)."""
|
||||
schedule_timezone: str | None = Field(default=None, max_length=64)
|
||||
schedule_daily_pipeline_cron: str | None = Field(default=None, max_length=120)
|
||||
schedule_dolt_earnings_cron: str | None = Field(default=None, max_length=120)
|
||||
schedule_sec_fundamentals_cron: str | None = Field(default=None, max_length=120)
|
||||
schedule_near_close_pipeline_cron: str | None = Field(default=None, max_length=120)
|
||||
schedule_after_close_pipeline_cron: str | None = Field(default=None, max_length=120)
|
||||
schedule_intraday_pipeline_cron: str | None = Field(default=None, max_length=120)
|
||||
schedule_fundamentals_cron: str | None = Field(default=None, max_length=120)
|
||||
schedule_backtest_cron: str | None = Field(default=None, max_length=120)
|
||||
schedule_ticker_universe_cron: str | None = Field(default=None, max_length=120)
|
||||
|
||||
|
||||
class PerformanceConfigUpdate(BaseModel):
|
||||
"""Window for the Performance comparison.
|
||||
|
||||
``start_date`` is an ISO date, or empty string to show all history. The
|
||||
strategy has been revised repeatedly; pinning a start keeps the shadow-vs-
|
||||
manual comparison inside one configuration instead of averaging across
|
||||
rules that no longer exist.
|
||||
"""
|
||||
start_date: str | None = Field(default=None, max_length=10)
|
||||
|
||||
|
||||
class ShadowBookConfigUpdate(BaseModel):
|
||||
"""Auto-traded shadow book: the validated strategy with no human input."""
|
||||
enabled: bool | None = None
|
||||
capacity: int | None = Field(default=None, ge=1, le=100)
|
||||
risk_pct: float | None = Field(default=None, gt=0, le=10)
|
||||
start_equity: float | None = Field(default=None, ge=1000)
|
||||
|
||||
|
||||
class SentimentConfigUpdate(BaseModel):
|
||||
|
||||
@@ -7,8 +7,75 @@ from datetime import date, datetime
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class MetricIndustry(BaseModel):
|
||||
label: str
|
||||
median: float
|
||||
favorable_percentile: int # 0-100, polarity-aware (higher = more favorable)
|
||||
peer_count: int
|
||||
|
||||
|
||||
class MetricHistoryPoint(BaseModel):
|
||||
period_end: str # YYYY-MM-DD
|
||||
value: float | None
|
||||
|
||||
|
||||
class MetricItem(BaseModel):
|
||||
key: str
|
||||
value: float | None = None
|
||||
history: list[MetricHistoryPoint] = []
|
||||
industry: MetricIndustry | None = None
|
||||
period_end: str | None = None
|
||||
filed_date: str | None = None
|
||||
caveat: str | None = None
|
||||
source: str = "sec"
|
||||
|
||||
|
||||
class EarningsNext(BaseModel):
|
||||
date: str
|
||||
session: str
|
||||
days_until: int
|
||||
|
||||
|
||||
class EarningsRecent(BaseModel):
|
||||
announce_date: str
|
||||
period_end: str | None = None
|
||||
eps_estimate: float | None = None
|
||||
eps_actual: float | None = None
|
||||
surprise_pct: float | None = None
|
||||
|
||||
|
||||
class EarningsObject(BaseModel):
|
||||
next: EarningsNext | None = None
|
||||
recent: list[EarningsRecent] = []
|
||||
|
||||
|
||||
class Valuation(BaseModel):
|
||||
pe: float | None = None
|
||||
fcf_yield: float | None = None
|
||||
market_cap_est: float | None = None
|
||||
pe_industry: MetricIndustry | None = None
|
||||
fcf_yield_industry: MetricIndustry | None = None
|
||||
price_date: str | None = None
|
||||
|
||||
|
||||
class FundamentalsReads(BaseModel):
|
||||
"""Deterministic text outputs, separate from the numeric metrics.
|
||||
|
||||
``by_key`` is a fixed map over every metric key plus ``pe`` and ``fcf_yield``,
|
||||
each a read string or null. ``header`` is null when there is no read at all."""
|
||||
|
||||
header: str | None = None
|
||||
by_key: dict[str, str | None] = {}
|
||||
|
||||
|
||||
class FundamentalResponse(BaseModel):
|
||||
"""Envelope-ready fundamental data response."""
|
||||
"""Envelope-ready fundamental data response.
|
||||
|
||||
Legacy fields are preserved unchanged (they come from ``fundamental_data`` /
|
||||
the legacy providers). The additive v1 objects — earnings, metrics, valuation,
|
||||
reads — are SEC/Dolt-derived and independent; a null legacy field is never
|
||||
mapped onto the new SEC metrics and vice-versa.
|
||||
"""
|
||||
|
||||
symbol: str
|
||||
pe_ratio: float | None = None
|
||||
@@ -18,3 +85,12 @@ class FundamentalResponse(BaseModel):
|
||||
next_earnings_date: date | None = None
|
||||
fetched_at: datetime | None = None
|
||||
unavailable_fields: dict[str, str] = {}
|
||||
|
||||
# --- additive v1 (always present; empty/null when unavailable) ---
|
||||
earnings: EarningsObject | None = None
|
||||
metrics: list[MetricItem] | None = None
|
||||
valuation: Valuation | None = None
|
||||
reads: FundamentalsReads | None = None
|
||||
setup_eligible: bool = True
|
||||
setup_block_code: str | None = None
|
||||
setup_block_reason: str | None = None
|
||||
|
||||
@@ -47,7 +47,13 @@ class PaperTradeResponse(BaseModel):
|
||||
alpha_pct: float | None = None
|
||||
alpha_usd: float | None = None
|
||||
close_reason: str | None = None
|
||||
# Execution era: null = pre-cutover / unknown; "near_close" = post schedule cutover.
|
||||
fill_mode: str | None = None
|
||||
# Live trailing-stop level + how far price sits above it (% ), for open trades
|
||||
# when the trailing exit policy is active.
|
||||
trailing_stop: float | None = None
|
||||
trailing_distance_pct: float | None = None
|
||||
# Trading sessions represented by post-entry OHLCV bars. These are populated
|
||||
# only while the active exit policy has a max-hold rule.
|
||||
sessions_held: int | None = None
|
||||
sessions_remaining: int | None = None
|
||||
|
||||
+23
-1
@@ -15,7 +15,9 @@ class SRLevelResult(BaseModel):
|
||||
price_level: float
|
||||
type: Literal["support", "resistance"]
|
||||
strength: int = Field(ge=0, le=100)
|
||||
detection_method: Literal["volume_profile", "pivot_point", "merged"]
|
||||
detection_method: Literal[
|
||||
"volume_profile", "pivot_point", "merged", "round_number"
|
||||
]
|
||||
created_at: datetime
|
||||
|
||||
|
||||
@@ -38,3 +40,23 @@ class SRLevelResponse(BaseModel):
|
||||
zones: list[SRZoneResult] = []
|
||||
visible_levels: list[SRLevelResult] = []
|
||||
count: int
|
||||
|
||||
|
||||
class GateTargetLevelResult(BaseModel):
|
||||
"""A transient Gate Target Ladder proposal for diagnostic display."""
|
||||
|
||||
price_level: float
|
||||
type: Literal["support", "resistance"]
|
||||
strength: int = Field(ge=0, le=100)
|
||||
detection_method: str
|
||||
sources: list[str] = Field(default_factory=list)
|
||||
traffic_count: int = Field(ge=0)
|
||||
|
||||
|
||||
class GateTargetLadderResponse(BaseModel):
|
||||
"""Volume-free Gate Target Ladder computed from current OHLCV history."""
|
||||
|
||||
symbol: str
|
||||
levels: list[GateTargetLevelResult]
|
||||
count: int
|
||||
lookback_bars: int
|
||||
|
||||
+12
-1
@@ -1,6 +1,6 @@
|
||||
"""Ticker request/response schemas."""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import date, datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -14,5 +14,16 @@ class TickerResponse(BaseModel):
|
||||
symbol: str
|
||||
name: str | None = None
|
||||
created_at: datetime
|
||||
# NULL == actively traded. Delisted symbols stay in the registry with their
|
||||
# history and are excluded from signals — the date is what makes that
|
||||
# visible instead of the row silently disappearing.
|
||||
delisted_on: date | None = None
|
||||
delisted_reason: str | None = None
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class TickerDelistingUpdate(BaseModel):
|
||||
delisted_on: date = Field(
|
||||
..., description="Effective date the symbol stopped trading"
|
||||
)
|
||||
|
||||
@@ -59,5 +59,6 @@ class TradeSetupResponse(BaseModel):
|
||||
momentum_percentile: float | None = None
|
||||
strategy_rank: float | None = None
|
||||
volatility_percentile: float | None = None
|
||||
reentry_gate_reset_required: bool = False
|
||||
context_as_of: TradeSetupContextAsOfResponse | None = None
|
||||
recommendation_summary: RecommendationSummaryResponse | None = None
|
||||
|
||||
+217
-66
@@ -7,6 +7,7 @@ from passlib.hash import bcrypt
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app import job_catalog
|
||||
from app.exceptions import DuplicateError, NotFoundError, ValidationError
|
||||
from app.models.fundamental import FundamentalData
|
||||
from app.models.ohlcv import OHLCVRecord
|
||||
@@ -17,7 +18,7 @@ from app.models.settings import SystemSetting
|
||||
from app.models.ticker import Ticker
|
||||
from app.models.trade_setup import TradeSetup
|
||||
from app.models.user import User
|
||||
from app.services import settings_store
|
||||
from app.services import job_run_store, settings_store
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -54,7 +55,9 @@ _ACTIVATION_BOOL_KEYS: dict[str, str] = {
|
||||
}
|
||||
ACTIVATION_DEFAULTS: dict[str, float | bool] = {
|
||||
"min_momentum_percentile": 80.0,
|
||||
"min_rr": 1.2,
|
||||
# Production floor from the 2026-07-12 min_rr sweep (in-sample and OOS peak).
|
||||
# 1.2 was the old code default and the trough next to the spike — do not restore.
|
||||
"min_rr": 2.0,
|
||||
# 0 = off. The July 2026 gate ablation showed the confidence floor added
|
||||
# nothing (identical net/trade with it removed, under both exit models)
|
||||
# while cutting ~25% of qualified trades.
|
||||
@@ -202,6 +205,61 @@ async def update_activation_config(
|
||||
return await get_activation_config(db)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Performance window + shadow book
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def get_performance_config(db: AsyncSession) -> dict:
|
||||
"""Start date for the Performance comparison ('' = all history)."""
|
||||
from app.services.paper_trade_service import KEY_PERFORMANCE_START
|
||||
|
||||
return {"start_date": await settings_store.get_value(db, KEY_PERFORMANCE_START, "") or ""}
|
||||
|
||||
|
||||
async def update_performance_config(db: AsyncSession, updates: dict) -> dict:
|
||||
"""Set (or clear) the performance start date. Empty string means all history."""
|
||||
from datetime import date as _date
|
||||
|
||||
from app.services.paper_trade_service import KEY_PERFORMANCE_START
|
||||
|
||||
if "start_date" in updates:
|
||||
raw = (updates.get("start_date") or "").strip()
|
||||
if raw:
|
||||
try:
|
||||
_date.fromisoformat(raw)
|
||||
except ValueError as exc:
|
||||
raise ValidationError("start_date must be an ISO date (YYYY-MM-DD)") from exc
|
||||
await update_setting(db, KEY_PERFORMANCE_START, raw)
|
||||
return await get_performance_config(db)
|
||||
|
||||
|
||||
async def get_shadow_book_config(db: AsyncSession) -> dict:
|
||||
"""Shadow book switch + sizing, with the validated defaults filled in."""
|
||||
from app.services import shadow_book_service
|
||||
|
||||
config = await shadow_book_service.get_config(db)
|
||||
config["enabled"] = await shadow_book_service.is_enabled(db)
|
||||
return config
|
||||
|
||||
|
||||
async def update_shadow_book_config(db: AsyncSession, updates: dict) -> dict:
|
||||
"""Update the shadow book. Enabling it starts automatic live entries."""
|
||||
from app.services import shadow_book_service
|
||||
|
||||
if "enabled" in updates:
|
||||
await update_setting(
|
||||
db, shadow_book_service.KEY_ENABLED, "true" if updates["enabled"] else "false"
|
||||
)
|
||||
for key, storage_key in (
|
||||
("capacity", shadow_book_service.KEY_CAPACITY),
|
||||
("risk_pct", shadow_book_service.KEY_RISK_PCT),
|
||||
("start_equity", shadow_book_service.KEY_START_EQUITY),
|
||||
):
|
||||
if key in updates:
|
||||
await update_setting(db, storage_key, str(updates[key]))
|
||||
return await get_shadow_book_config(db)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pipeline schedule (cron)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -316,14 +374,18 @@ async def update_ticker_universe_default(db: AsyncSession, universe: str) -> dic
|
||||
# Data cleanup
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def cleanup_data(db: AsyncSession, older_than_days: int) -> dict[str, int]:
|
||||
async def cleanup_data(db: AsyncSession, older_than_days: int) -> dict:
|
||||
"""Delete OHLCV, sentiment, and fundamental records older than N days.
|
||||
|
||||
Preserves tickers, users, and latest scores.
|
||||
Returns a dict with counts of deleted records per table.
|
||||
Preserves tickers, users, and latest scores. After OHLCV pruning, rebuilds
|
||||
Structural S/R for every ticker so chart levels match the remaining history.
|
||||
|
||||
Returns deleted-row counts plus S/R refresh outcomes. A per-ticker S/R
|
||||
failure rolls the session back (so later tickers still run) and is listed
|
||||
in ``sr_refresh_failures`` rather than aborting the whole cleanup.
|
||||
"""
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=older_than_days)
|
||||
counts: dict[str, int] = {}
|
||||
counts: dict = {}
|
||||
|
||||
# OHLCV — date column is a date, compare with cutoff date
|
||||
result = await db.execute(
|
||||
@@ -344,6 +406,36 @@ async def cleanup_data(db: AsyncSession, older_than_days: int) -> dict[str, int]
|
||||
counts["fundamentals"] = result.rowcount # type: ignore[assignment]
|
||||
|
||||
await db.commit()
|
||||
|
||||
counts["sr_refresh_ok"] = 0
|
||||
counts["sr_refresh_failed"] = 0
|
||||
counts["sr_refresh_failures"] = []
|
||||
|
||||
# Structural S/R is derived from OHLCV; recompute after history shrinks.
|
||||
if counts["ohlcv"]:
|
||||
from app.services.sr_service import recalculate_sr_levels
|
||||
|
||||
symbols = list(
|
||||
(await db.execute(select(Ticker.symbol).order_by(Ticker.symbol))).scalars().all()
|
||||
)
|
||||
for symbol in symbols:
|
||||
try:
|
||||
await recalculate_sr_levels(db, symbol)
|
||||
counts["sr_refresh_ok"] += 1
|
||||
except Exception as exc:
|
||||
logger.exception("S/R refresh after cleanup failed for %s", symbol)
|
||||
try:
|
||||
await db.rollback()
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Session rollback after S/R cleanup failure also failed for %s",
|
||||
symbol,
|
||||
)
|
||||
counts["sr_refresh_failed"] += 1
|
||||
counts["sr_refresh_failures"].append(
|
||||
{"symbol": symbol, "error": f"{type(exc).__name__}: {exc}"}
|
||||
)
|
||||
|
||||
return counts
|
||||
|
||||
|
||||
@@ -515,80 +607,110 @@ async def get_pipeline_readiness(db: AsyncSession) -> list[dict]:
|
||||
# Job control (placeholder — scheduler is Task 12.1)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
VALID_JOB_NAMES = {
|
||||
"data_collector",
|
||||
"data_backfill",
|
||||
"benchmark_collector",
|
||||
"sentiment_collector",
|
||||
"fundamental_collector",
|
||||
"rr_scanner",
|
||||
"ticker_universe_sync",
|
||||
"outcome_evaluator",
|
||||
"alerts",
|
||||
"market_regime",
|
||||
"regime_monitor",
|
||||
"event_study",
|
||||
"backtest",
|
||||
"daily_pipeline",
|
||||
"intraday_pipeline",
|
||||
}
|
||||
# Job identity, labels and pipeline membership now live in app.job_catalog, which
|
||||
# derives PIPELINE_MEMBERS from the pipeline step lists instead of restating them.
|
||||
# Re-exported here because callers (routers, tests) import them from this module.
|
||||
VALID_JOB_NAMES = job_catalog.VALID_JOB_NAMES
|
||||
JOB_LABELS = job_catalog.JOB_LABELS
|
||||
PIPELINE_MEMBERS = job_catalog.PIPELINE_MEMBERS
|
||||
|
||||
JOB_LABELS = {
|
||||
"data_collector": "Data Collector (OHLCV)",
|
||||
"data_backfill": "Data Backfill (deep history)",
|
||||
"benchmark_collector": "Benchmark Collector",
|
||||
"sentiment_collector": "Sentiment Collector",
|
||||
"fundamental_collector": "Fundamental Collector",
|
||||
"rr_scanner": "R:R Scanner",
|
||||
"ticker_universe_sync": "Ticker Universe Sync",
|
||||
"outcome_evaluator": "Outcome Evaluator",
|
||||
"alerts": "Alerts Dispatcher",
|
||||
"market_regime": "Market Regime",
|
||||
"regime_monitor": "Regime Monitor",
|
||||
"event_study": "Event Study",
|
||||
"backtest": "Backtest",
|
||||
"daily_pipeline": "Daily Pipeline",
|
||||
"intraday_pipeline": "Intraday Pipeline",
|
||||
}
|
||||
# Anything further out than this is a parked backstop, not a schedule: pipeline
|
||||
# steps and manual jobs are registered on a 520-week interval, and triggering one
|
||||
# re-arms it. Belt-and-braces behind the category rule in _next_run_fields.
|
||||
_NEXT_RUN_HORIZON_DAYS = 365
|
||||
|
||||
# Jobs driven by the daily_pipeline (in order) rather than their own timer.
|
||||
PIPELINE_MEMBERS = {
|
||||
"data_collector",
|
||||
"benchmark_collector",
|
||||
"sentiment_collector",
|
||||
"rr_scanner",
|
||||
"outcome_evaluator",
|
||||
"market_regime",
|
||||
"regime_monitor",
|
||||
}
|
||||
|
||||
def _visible_next_run(next_run: datetime | None) -> datetime | None:
|
||||
"""Drop a next-run that is really the parked backstop."""
|
||||
if next_run is None:
|
||||
return None
|
||||
horizon = datetime.now(next_run.tzinfo) + timedelta(days=_NEXT_RUN_HORIZON_DAYS)
|
||||
return None if next_run > horizon else next_run
|
||||
|
||||
|
||||
def _own_next_run(scheduler, name: str) -> datetime | None:
|
||||
# getattr: APScheduler only sets next_run_time once the scheduler is running,
|
||||
# so a job registered but not yet started has no such attribute at all.
|
||||
job = scheduler.get_job(name)
|
||||
return _visible_next_run(getattr(job, "next_run_time", None)) if job else None
|
||||
|
||||
|
||||
def _next_run_fields(scheduler, name: str, enabled_map: dict[str, bool]) -> dict:
|
||||
"""Where this job's next run comes from, decided by category not by clock.
|
||||
|
||||
A pipeline step has no meaningful schedule of its own, so reporting one is
|
||||
the bug: its parent's timer is the answer. Manual jobs have no answer at all,
|
||||
and saying so beats rendering a parked backstop as a date.
|
||||
"""
|
||||
category = job_catalog.JOB_CATEGORY.get(name)
|
||||
if category == job_catalog.CATEGORY_STEP:
|
||||
parents = job_catalog.PIPELINES_BY_MEMBER.get(name, ())
|
||||
soonest: datetime | None = None
|
||||
via: str | None = None
|
||||
for parent in parents:
|
||||
if not enabled_map.get(parent, True):
|
||||
continue
|
||||
candidate = _own_next_run(scheduler, parent)
|
||||
if candidate is not None and (soonest is None or candidate < soonest):
|
||||
soonest, via = candidate, parent
|
||||
return {
|
||||
"next_run_at": None,
|
||||
"next_run_source": "via_pipeline",
|
||||
"via_next_run_at": soonest.isoformat() if soonest else None,
|
||||
"via_next_run_job": via,
|
||||
}
|
||||
if category == job_catalog.CATEGORY_MANUAL:
|
||||
return {
|
||||
"next_run_at": None,
|
||||
"next_run_source": "manual_only",
|
||||
"via_next_run_at": None,
|
||||
"via_next_run_job": None,
|
||||
}
|
||||
own = _own_next_run(scheduler, name)
|
||||
return {
|
||||
"next_run_at": own.isoformat() if own else None,
|
||||
"next_run_source": "own_schedule",
|
||||
"via_next_run_at": None,
|
||||
"via_next_run_job": None,
|
||||
}
|
||||
|
||||
|
||||
async def list_jobs(db: AsyncSession) -> list[dict]:
|
||||
"""Return status of all scheduled jobs."""
|
||||
"""Return status of all scheduled jobs, grouped and ordered by category."""
|
||||
from app.scheduler import get_job_runtime_snapshot, scheduler
|
||||
|
||||
visible = sorted(VALID_JOB_NAMES - job_catalog.HIDDEN_JOBS, key=job_catalog.sort_order)
|
||||
# One query for every flag instead of one per job. Parents are read too, since
|
||||
# a step reports its parent's next run only while that parent is enabled.
|
||||
flags = await settings_store.get_map(
|
||||
db, [f"job_{name}_enabled" for name in VALID_JOB_NAMES]
|
||||
)
|
||||
enabled_map = {
|
||||
name: flags.get(f"job_{name}_enabled", "true") == "true"
|
||||
for name in VALID_JOB_NAMES
|
||||
}
|
||||
last_runs = await job_run_store.get_map(db, visible)
|
||||
|
||||
jobs_out = []
|
||||
for name in sorted(VALID_JOB_NAMES):
|
||||
# Check enabled setting
|
||||
setting = await settings_store.get_setting(db, f"job_{name}_enabled")
|
||||
enabled = setting.value == "true" if setting else True # default enabled
|
||||
|
||||
# Get scheduler job info
|
||||
for name in visible:
|
||||
job = scheduler.get_job(name)
|
||||
next_run = None
|
||||
if job and job.next_run_time:
|
||||
next_run = job.next_run_time.isoformat()
|
||||
|
||||
runtime = get_job_runtime_snapshot(name)
|
||||
last = last_runs.get(name)
|
||||
|
||||
jobs_out.append({
|
||||
"name": name,
|
||||
"label": JOB_LABELS.get(name, name),
|
||||
"enabled": enabled,
|
||||
"next_run_at": next_run,
|
||||
"via_pipeline": name in PIPELINE_MEMBERS,
|
||||
"enabled": enabled_map.get(name, True),
|
||||
"category": job_catalog.JOB_CATEGORY.get(name),
|
||||
"sort_order": job_catalog.sort_order(name),
|
||||
# Parent pipelines for a step; the steps themselves for a pipeline.
|
||||
"pipelines": list(job_catalog.PIPELINES_BY_MEMBER.get(name, ())),
|
||||
"steps": [step for step, _ in job_catalog.PIPELINE_STEPS.get(name, ())],
|
||||
"registered": job is not None,
|
||||
"running": bool(runtime.get("running", False)),
|
||||
# runtime_* are strictly live in-memory state. Persisted history is
|
||||
# reported separately as last_run_*, so a stale error cannot pin the
|
||||
# status chip or the rate-limit banner.
|
||||
"runtime_status": runtime.get("status"),
|
||||
"runtime_processed": runtime.get("processed"),
|
||||
"runtime_total": runtime.get("total"),
|
||||
@@ -597,18 +719,37 @@ async def list_jobs(db: AsyncSession) -> list[dict]:
|
||||
"runtime_started_at": runtime.get("started_at"),
|
||||
"runtime_finished_at": runtime.get("finished_at"),
|
||||
"runtime_message": runtime.get("message"),
|
||||
# Survives restarts, unlike runtime_*. Reported separately so the
|
||||
# status chip keeps meaning "state now" rather than "last outcome,
|
||||
# forever" -- an error a week ago must not read as Inactive today.
|
||||
"last_run_at": last.finished_at.isoformat() if last else None,
|
||||
"last_run_status": last.status if last else None,
|
||||
"last_run_message": last.message if last else None,
|
||||
"last_run_processed": last.processed if last else None,
|
||||
"last_run_total": last.total if last else None,
|
||||
**_next_run_fields(scheduler, name, enabled_map),
|
||||
})
|
||||
|
||||
return jobs_out
|
||||
|
||||
|
||||
async def trigger_job(db: AsyncSession, job_name: str) -> dict[str, str]:
|
||||
async def trigger_job(
|
||||
db: AsyncSession,
|
||||
job_name: str,
|
||||
*,
|
||||
target_model: str | None = None,
|
||||
cadence: str | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Trigger a manual job run via the scheduler.
|
||||
|
||||
Runs the job immediately (in addition to its regular schedule).
|
||||
"""
|
||||
if job_name not in VALID_JOB_NAMES:
|
||||
raise ValidationError(f"Unknown job: {job_name}. Valid jobs: {', '.join(sorted(VALID_JOB_NAMES))}")
|
||||
if target_model is not None and job_name != "backtest":
|
||||
raise ValidationError("target_model is supported only for the backtest job")
|
||||
if cadence is not None and job_name != "backtest":
|
||||
raise ValidationError("cadence is supported only for the backtest job")
|
||||
|
||||
from app.scheduler import get_job_runtime_snapshot, scheduler
|
||||
|
||||
@@ -635,11 +776,21 @@ async def trigger_job(db: AsyncSession, job_name: str) -> dict[str, str]:
|
||||
if job is None:
|
||||
return {"job": job_name, "status": "not_found", "message": f"Job '{job_name}' is not registered in the scheduler"}
|
||||
|
||||
if job_name == "backtest":
|
||||
from app.scheduler import queue_backtest_options
|
||||
|
||||
target_model, cadence = queue_backtest_options(target_model, cadence)
|
||||
|
||||
job.modify(next_run_time=None) # Reset, then trigger immediately
|
||||
from datetime import datetime, timezone
|
||||
job.modify(next_run_time=datetime.now(timezone.utc))
|
||||
|
||||
return {"job": job_name, "status": "triggered", "message": f"Job '{job_name}' triggered for immediate execution"}
|
||||
result = {"job": job_name, "status": "triggered", "message": f"Job '{job_name}' triggered for immediate execution"}
|
||||
if target_model is not None:
|
||||
result["target_model"] = target_model
|
||||
if cadence is not None:
|
||||
result["cadence"] = cadence
|
||||
return result
|
||||
|
||||
|
||||
async def toggle_job(db: AsyncSession, job_name: str, enabled: bool) -> SystemSetting:
|
||||
|
||||
+224
-56
@@ -29,6 +29,7 @@ from app.config import settings
|
||||
from app.models.alert import AlertLog
|
||||
from app.models.ohlcv import OHLCVRecord
|
||||
from app.models.paper_trade import PaperTrade
|
||||
from app.services.trade_policy import MANUAL_BOOK
|
||||
from app.models.score import CompositeScore
|
||||
from app.models.sr_level import SRLevel
|
||||
from app.models.ticker import Ticker
|
||||
@@ -58,7 +59,9 @@ _BOOL_DEFAULTS = {
|
||||
KEY_SR: True,
|
||||
KEY_SCORE_DROP: True,
|
||||
KEY_DIGEST: True,
|
||||
KEY_REGIME_QUADRANT: True,
|
||||
# Experimental human-facing thermometer: opt in explicitly. Existing stored
|
||||
# true values remain true; only missing/reset configurations default off.
|
||||
KEY_REGIME_QUADRANT: False,
|
||||
KEY_TRADE_CLOSED: True,
|
||||
}
|
||||
|
||||
@@ -90,19 +93,27 @@ SIGNAL_BUNDLE_SECTIONS = (
|
||||
)
|
||||
SIGNAL_BUNDLE_MAX_CHARS = 3900 # Telegram limit is 4096; keep room for HTML parsing
|
||||
|
||||
# Regime quadrant-change alert: (regime index x early-warning) quadrant.
|
||||
# Regime quadrant-change alert: (State x Warning) quadrant.
|
||||
# Hysteresis (a deadband around each divider) stops a point sitting on a boundary
|
||||
# from flip-flopping; the cooldown caps how often a genuine change can re-alert.
|
||||
QUAD_TYPE = "regime_quadrant"
|
||||
QUAD_X_DIV = 40.0 # regime index divider (matches the frontend quadrant)
|
||||
QUAD_Y_DIV = 60.0 # early-warning divider
|
||||
# The fundamental channel gets its own alerts rather than shifting a score:
|
||||
# "the context changed" and "both channels are elevated" are different facts from
|
||||
# "the market axes moved", and fusing them into one number would destroy exactly
|
||||
# the information an operator uses to decide how much the alert is worth.
|
||||
FUND_TYPE = "regime_fundamental"
|
||||
CONFLUENCE_TYPE = "regime_confluence"
|
||||
# States that count as fundamental risk for the confluence test.
|
||||
FUND_ADVERSE = "adverse"
|
||||
QUAD_X_DIV = 50.0 # v3 State divider (backend response is authoritative)
|
||||
QUAD_Y_DIV = 40.0 # v3 Warning divider; the axes have different ranges
|
||||
QUAD_MARGIN = 5.0 # half-width of the hysteresis deadband around each divider
|
||||
QUAD_COOLDOWN_DAYS = 3 # min days between quadrant-change alerts
|
||||
QUAD_LABELS = {
|
||||
"1": "① Hot & brittle",
|
||||
"2": "② Transition",
|
||||
"3": "③ Healthy & broad",
|
||||
"4": "④ Real downturn",
|
||||
"1": "Early warning",
|
||||
"2": "Active stress",
|
||||
"3": "Healthy",
|
||||
"4": "Stressed / stabilizing",
|
||||
}
|
||||
|
||||
AlertItem = tuple[str, str, str] # alert_type, dedup_key, text
|
||||
@@ -258,17 +269,6 @@ def _log_alert(db: AsyncSession, alert_type: str, key: str, value: float | None
|
||||
)
|
||||
|
||||
|
||||
async def _watermark(db: AsyncSession, symbol: str) -> float | None:
|
||||
result = await db.execute(
|
||||
select(AlertLog.value)
|
||||
.where(AlertLog.alert_type == WATERMARK_TYPE, AlertLog.dedup_key == symbol)
|
||||
.order_by(AlertLog.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
row = result.first()
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Trigger collectors
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -291,6 +291,7 @@ async def _qualified_setups(db: AsyncSession) -> list[dict]:
|
||||
db,
|
||||
live_recommendation=True,
|
||||
exclude_open_trade_tickers=True,
|
||||
exclude_reentry_gate_locked_tickers=True,
|
||||
)
|
||||
config = await get_activation_config(db)
|
||||
return [s for s in setups if setup_qualifies(SimpleNamespace(**s), config)]
|
||||
@@ -640,6 +641,10 @@ async def _collect_closed_trades(db: AsyncSession) -> list[ClosedTradeItem]:
|
||||
PaperTrade.closed_at.is_not(None),
|
||||
PaperTrade.closed_at > cutoff,
|
||||
PaperTrade.close_reason.in_(("trailing", "stop", "target", "time")),
|
||||
# Your own positions only — shadow trades are a research record, not
|
||||
# something you hold, and mixing them in unlabelled reads as if you
|
||||
# were stopped out of a name you never took.
|
||||
PaperTrade.book == MANUAL_BOOK,
|
||||
)
|
||||
.order_by(PaperTrade.closed_at.desc())
|
||||
)
|
||||
@@ -650,8 +655,14 @@ async def _collect_closed_trades(db: AsyncSession) -> list[ClosedTradeItem]:
|
||||
|
||||
|
||||
async def _paper_book_value(db: AsyncSession) -> float:
|
||||
"""Paper-trade equity: fixed capital plus realized/unrealized P&L."""
|
||||
result = await db.execute(select(PaperTrade))
|
||||
"""Paper-trade equity: fixed capital plus realized/unrealized P&L.
|
||||
|
||||
Discretionary book only — the shadow book runs on its own notional equity
|
||||
and folding it in would report a number matching neither book.
|
||||
"""
|
||||
result = await db.execute(
|
||||
select(PaperTrade).where(PaperTrade.book == MANUAL_BOOK)
|
||||
)
|
||||
trades = list(result.scalars().all())
|
||||
latest: dict[int, float | None] = {}
|
||||
for trade in trades:
|
||||
@@ -704,49 +715,65 @@ def _closed_trade_bundle(
|
||||
|
||||
def _bools_to_quadrant(x_high: bool, y_high: bool) -> str:
|
||||
if y_high:
|
||||
return "2" if x_high else "1" # ② Transition / ① Hot & brittle
|
||||
return "4" if x_high else "3" # ④ Real downturn / ③ Healthy & broad
|
||||
return "2" if x_high else "1" # Active stress / Early warning
|
||||
return "4" if x_high else "3" # Stressed/stabilizing / Healthy
|
||||
|
||||
|
||||
def _quadrant_to_bools(q: str) -> tuple[bool, bool]:
|
||||
return {"1": (False, True), "2": (True, True), "3": (False, False), "4": (True, False)}[q]
|
||||
|
||||
|
||||
def _classify_quadrant(x: float, y: float, prev: str | None, margin: float = QUAD_MARGIN) -> str:
|
||||
"""Quadrant of (regime index x, early warning y), with per-axis hysteresis.
|
||||
def _classify_quadrant(
|
||||
x: float,
|
||||
y: float,
|
||||
prev: str | None,
|
||||
margin: float = QUAD_MARGIN,
|
||||
x_div: float = QUAD_X_DIV,
|
||||
y_div: float = QUAD_Y_DIV,
|
||||
) -> str:
|
||||
"""Quadrant of (State x, Warning y), with per-axis hysteresis.
|
||||
|
||||
Each axis only flips once the value crosses its divider by ``margin`` in the
|
||||
new direction, so a point parked on a divider keeps its current quadrant
|
||||
instead of flip-flopping. ``prev`` None means a fresh (no-hysteresis) classify.
|
||||
"""
|
||||
if prev is None:
|
||||
return _bools_to_quadrant(x >= QUAD_X_DIV, y >= QUAD_Y_DIV)
|
||||
return _bools_to_quadrant(x >= x_div, y >= y_div)
|
||||
px, py = _quadrant_to_bools(prev)
|
||||
x_high = (x >= QUAD_X_DIV - margin) if px else (x >= QUAD_X_DIV + margin)
|
||||
y_high = (y >= QUAD_Y_DIV - margin) if py else (y >= QUAD_Y_DIV + margin)
|
||||
x_high = (x >= x_div - margin) if px else (x >= x_div + margin)
|
||||
y_high = (y >= y_div - margin) if py else (y >= y_div + margin)
|
||||
return _bools_to_quadrant(x_high, y_high)
|
||||
|
||||
|
||||
def _quadrant_log_key(q: str, x: float, y: float) -> str:
|
||||
return f"{q}:{x:.1f}:{y:.1f}"
|
||||
def _quadrant_log_key(q: str, x: float, y: float, basket_hash: str | None = None) -> str:
|
||||
return f"{basket_hash or 'legacy'}:{q}:{x:.1f}:{y:.1f}"
|
||||
|
||||
|
||||
def _parse_quadrant_log_key(key: str | None) -> tuple[str | None, float | None, float | None]:
|
||||
def _parse_quadrant_log_key(
|
||||
key: str | None,
|
||||
) -> tuple[str | None, str | None, float | None, float | None]:
|
||||
if not key:
|
||||
return None, None, None
|
||||
return None, None, None, None
|
||||
parts = key.split(":")
|
||||
q = parts[0]
|
||||
if parts[0] in QUAD_LABELS:
|
||||
basket_hash, q, values = None, parts[0], parts[1:]
|
||||
elif len(parts) >= 2:
|
||||
basket_hash, q, values = parts[0], parts[1], parts[2:]
|
||||
else:
|
||||
return None, None, None, None
|
||||
if q not in QUAD_LABELS:
|
||||
return None, None, None
|
||||
if len(parts) >= 3:
|
||||
return None, None, None, None
|
||||
if len(values) >= 2:
|
||||
try:
|
||||
return q, float(parts[1]), float(parts[2])
|
||||
return basket_hash, q, float(values[0]), float(values[1])
|
||||
except ValueError:
|
||||
pass
|
||||
return q, None, None
|
||||
return basket_hash, q, None, None
|
||||
|
||||
|
||||
async def _last_quadrant(db: AsyncSession) -> tuple[str | None, float | None, float | None, datetime | None]:
|
||||
async def _last_quadrant(
|
||||
db: AsyncSession,
|
||||
) -> tuple[str | None, str | None, float | None, float | None, datetime | None]:
|
||||
"""Most recently logged quadrant (and when), our baseline for change + cooldown."""
|
||||
result = await db.execute(
|
||||
select(AlertLog.dedup_key, AlertLog.created_at)
|
||||
@@ -756,9 +783,9 @@ async def _last_quadrant(db: AsyncSession) -> tuple[str | None, float | None, fl
|
||||
)
|
||||
row = result.first()
|
||||
if not row:
|
||||
return None, None, None, None
|
||||
prev_q, prev_x, prev_y = _parse_quadrant_log_key(row[0])
|
||||
return prev_q, prev_x, prev_y, row[1]
|
||||
return None, None, None, None, None
|
||||
basket_hash, prev_q, prev_x, prev_y = _parse_quadrant_log_key(row[0])
|
||||
return basket_hash, prev_q, prev_x, prev_y, row[1]
|
||||
|
||||
|
||||
async def _collect_regime_quadrant(db: AsyncSession) -> list[tuple[str, str]]:
|
||||
@@ -769,25 +796,64 @@ async def _collect_regime_quadrant(db: AsyncSession) -> list[tuple[str, str]]:
|
||||
cooldown has elapsed. The dispatch loop logs the new quadrant on send, which
|
||||
becomes the next baseline and resets the cooldown clock.
|
||||
"""
|
||||
from app.services.regime_monitor_service import get_regime_monitor
|
||||
from app.services.regime_monitor_service import get_regime_history, get_regime_monitor
|
||||
|
||||
data = await get_regime_monitor(db)
|
||||
if not data.get("available"):
|
||||
return []
|
||||
x = data.get("total_score")
|
||||
y = (data.get("early_warning") or {}).get("score")
|
||||
state = data.get("state") or {}
|
||||
warning = data.get("warning") or {}
|
||||
x = state.get("score")
|
||||
y = warning.get("score")
|
||||
if x is None or y is None:
|
||||
return []
|
||||
|
||||
prev, prev_x, prev_y, prev_time = await _last_quadrant(db)
|
||||
if prev is None:
|
||||
_log_alert(db, QUAD_TYPE, _quadrant_log_key(_classify_quadrant(x, y, None), x, y)) # seed, no alert
|
||||
quality = data.get("data_quality") or {}
|
||||
if (
|
||||
float(state.get("coverage") or 0) < 75
|
||||
or float(warning.get("coverage") or 0) < 75
|
||||
or not quality.get("is_fresh")
|
||||
):
|
||||
return []
|
||||
|
||||
new_q = _classify_quadrant(x, y, prev)
|
||||
quadrant_cfg = data.get("quadrant_config") or {}
|
||||
x_div = float(quadrant_cfg.get("state_divider", QUAD_X_DIV))
|
||||
y_div = float(quadrant_cfg.get("warning_divider", QUAD_Y_DIV))
|
||||
margin = float(quadrant_cfg.get("margin", QUAD_MARGIN))
|
||||
basket_hash = str((data.get("basket") or {}).get("hash") or "unknown")
|
||||
|
||||
prev_hash, prev, prev_x, prev_y, prev_time = await _last_quadrant(db)
|
||||
if prev is None or prev_hash != basket_hash:
|
||||
seed = _classify_quadrant(x, y, None, margin, x_div, y_div)
|
||||
_log_alert(db, QUAD_TYPE, _quadrant_log_key(seed, x, y, basket_hash))
|
||||
return []
|
||||
|
||||
new_q = _classify_quadrant(x, y, prev, margin, x_div, y_div)
|
||||
if new_q == prev:
|
||||
return []
|
||||
|
||||
history = await get_regime_history(db, days=14)
|
||||
valid = [
|
||||
point for point in history
|
||||
if point.get("state") is not None
|
||||
and point.get("warning") is not None
|
||||
and float(point.get("state_coverage") or 0) >= 75
|
||||
and float(point.get("warning_coverage") or 0) >= 75
|
||||
]
|
||||
if len(valid) < 2:
|
||||
return []
|
||||
prior = valid[-2]
|
||||
prior_q = _classify_quadrant(
|
||||
float(prior["state"]),
|
||||
float(prior["warning"]),
|
||||
prev,
|
||||
margin,
|
||||
x_div,
|
||||
y_div,
|
||||
)
|
||||
if prior_q != new_q:
|
||||
return []
|
||||
|
||||
if prev_time is not None:
|
||||
if prev_time.tzinfo is None:
|
||||
prev_time = prev_time.replace(tzinfo=timezone.utc)
|
||||
@@ -796,17 +862,114 @@ async def _collect_regime_quadrant(db: AsyncSession) -> list[tuple[str, str]]:
|
||||
|
||||
if prev_x is not None and prev_y is not None:
|
||||
metrics = (
|
||||
f"regime {prev_x:.0f} → {x:.0f} ({x - prev_x:+.0f}) · "
|
||||
f"early-warning {prev_y:.0f} → {y:.0f} ({y - prev_y:+.0f})"
|
||||
f"State {prev_x:.0f} → {x:.0f} ({x - prev_x:+.0f}) · "
|
||||
f"Warning {prev_y:.0f} → {y:.0f} ({y - prev_y:+.0f})"
|
||||
)
|
||||
else:
|
||||
metrics = f"regime {x:.0f} · early-warning {y:.0f}"
|
||||
text = (
|
||||
f"🧭 <b>Regime quadrant change</b>\n"
|
||||
f"{QUAD_LABELS.get(prev, prev)} → {QUAD_LABELS.get(new_q, new_q)}\n"
|
||||
f"{metrics}"
|
||||
metrics = f"State {x:.0f} · Warning {y:.0f}"
|
||||
# The fundamental channel is reported, never added in: this alert is about
|
||||
# the two market axes, and the context is stated beside them so a reader can
|
||||
# judge confluence themselves rather than being handed a fused number.
|
||||
context = data.get("fundamental_context") or {}
|
||||
context_line = (
|
||||
f"fundamentals: {context.get('state', 'unknown')} "
|
||||
f"({context.get('evidence_quality', 'unavailable')})\n"
|
||||
)
|
||||
return [(_quadrant_log_key(new_q, x, y), text)]
|
||||
text = (
|
||||
f"🧭 <b>AI/Tech risk quadrant change</b>\n"
|
||||
f"{QUAD_LABELS.get(prev, prev)} → {QUAD_LABELS.get(new_q, new_q)}\n"
|
||||
f"{metrics}\n"
|
||||
f"{context_line}"
|
||||
f"coverage: state {state.get('coverage'):.0f}% / warning {warning.get('coverage'):.0f}%\n"
|
||||
f"<i>Risk thermometer - not a trade signal.</i>"
|
||||
)
|
||||
return [(_quadrant_log_key(new_q, x, y, basket_hash), text)]
|
||||
|
||||
|
||||
async def _last_logged_key(db: AsyncSession, alert_type: str) -> str | None:
|
||||
"""Most recent logged key for a type, our baseline for change detection."""
|
||||
result = await db.execute(
|
||||
select(AlertLog.dedup_key)
|
||||
.where(AlertLog.alert_type == alert_type)
|
||||
.order_by(AlertLog.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
row = result.first()
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
async def _collect_regime_fundamental(db: AsyncSession) -> list[tuple[str, str, str]]:
|
||||
"""Fundamental-context changes and market/fundamental confluence.
|
||||
|
||||
Two triggers, deliberately separate from the quadrant alert and from each
|
||||
other, because they answer different questions: *what the evidence says* and
|
||||
*whether both channels agree*. Neither is derived by moving a score.
|
||||
|
||||
``unknown`` never alerts. An absence of evidence is not a change in the
|
||||
evidence, and alerting on it would train the reader to ignore the channel.
|
||||
Both seed silently on first run, exactly as the quadrant alert does.
|
||||
"""
|
||||
from app.services.regime_monitor_service import get_regime_monitor
|
||||
|
||||
data = await get_regime_monitor(db)
|
||||
if not data.get("available"):
|
||||
return []
|
||||
warning = data.get("warning") or {}
|
||||
context = data.get("fundamental_context") or {}
|
||||
state = str(context.get("state") or "unknown")
|
||||
# `usable`, not `available`: the state is deliberately preserved past its
|
||||
# staleness horizon so the card can keep showing the last thing observed, and
|
||||
# an observation whose extraction failed is fresh but knows nothing. Neither
|
||||
# may confirm anything — without this gate a months-old adverse read silently
|
||||
# corroborates every new Warning crossing forever, which is the strongest
|
||||
# claim this channel makes and the one it has least right to make.
|
||||
usable = bool(context.get("usable"))
|
||||
score = warning.get("score")
|
||||
|
||||
quality = data.get("data_quality") or {}
|
||||
if not quality.get("is_fresh") or float(warning.get("coverage") or 0) < 75:
|
||||
return []
|
||||
|
||||
quadrant_cfg = data.get("quadrant_config") or {}
|
||||
y_div = float(quadrant_cfg.get("warning_divider", QUAD_Y_DIV))
|
||||
warning_elevated = score is not None and float(score) >= y_div
|
||||
|
||||
out: list[tuple[str, str, str]] = []
|
||||
|
||||
previous_state = await _last_logged_key(db, FUND_TYPE)
|
||||
if previous_state is None:
|
||||
_log_alert(db, FUND_TYPE, state) # seed
|
||||
elif previous_state != state and state != "unknown" and usable:
|
||||
effective = context.get("effective_date")
|
||||
out.append((
|
||||
FUND_TYPE,
|
||||
state,
|
||||
f"📋 <b>Fundamental context changed</b>\n"
|
||||
f"{previous_state} → {state}\n"
|
||||
f"evidence: {context.get('evidence_quality', 'unavailable')}"
|
||||
+ (f" · effective {effective}" if effective else "")
|
||||
+ "\n<i>Context channel — not a score, not a trade signal.</i>",
|
||||
))
|
||||
|
||||
confluence = "yes" if (warning_elevated and state == FUND_ADVERSE and usable) else "no"
|
||||
previous_confluence = await _last_logged_key(db, CONFLUENCE_TYPE)
|
||||
if previous_confluence is None:
|
||||
_log_alert(db, CONFLUENCE_TYPE, confluence) # seed
|
||||
elif previous_confluence != confluence and confluence == "yes":
|
||||
out.append((
|
||||
CONFLUENCE_TYPE,
|
||||
confluence,
|
||||
f"⚠️ <b>Confluence: market and fundamental risk both elevated</b>\n"
|
||||
f"Warning {float(score):.0f} (≥ {y_div:.0f}) with fundamentals {state}\n"
|
||||
f"evidence: {context.get('evidence_quality', 'unavailable')}\n"
|
||||
f"<i>Highest attention. Still a thermometer — not a trade signal.</i>",
|
||||
))
|
||||
elif previous_confluence != confluence:
|
||||
# Falling out of confluence is a state change worth recording as the new
|
||||
# baseline, but not worth a message.
|
||||
_log_alert(db, CONFLUENCE_TYPE, confluence)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -901,6 +1064,11 @@ async def dispatch_alerts(db: AsyncSession) -> dict:
|
||||
# cooldown/hysteresis handled in the collector (like score drops)
|
||||
for key, text in await _collect_regime_quadrant(db):
|
||||
outgoing.append((QUAD_TYPE, key, text))
|
||||
# Deliberately three separate messages off one toggle, not one fused
|
||||
# signal: the market axes and the fundamental channel are different kinds
|
||||
# of evidence, and an operator needs to know which one moved.
|
||||
for alert_type, key, text in await _collect_regime_fundamental(db):
|
||||
outgoing.append((alert_type, key, text))
|
||||
|
||||
if cfg["trade_closed"]:
|
||||
for key, text, pnl_usd in await _collect_closed_trades(db):
|
||||
|
||||
+2085
-212
File diff suppressed because it is too large
Load Diff
@@ -1,18 +1,19 @@
|
||||
"""Market-breadth early-warning indicator (from the stored universe OHLCV).
|
||||
"""Market-breadth state and early-warning indicators.
|
||||
|
||||
Breadth is a genuinely *leading* construct: a few mega-caps can keep an index
|
||||
rising while participation narrows underneath — the classic pre-top divergence.
|
||||
We measure it from the OHLCV we already store for the whole universe, so it costs
|
||||
no new data source.
|
||||
V2 measures an explicit, frozen basket rather than every ticker currently stored
|
||||
in the database. That keeps the live series reproducible when the wider product
|
||||
universe changes.
|
||||
|
||||
Two layers:
|
||||
- breadth = % of the universe trading above its own 200-DMA (0-100).
|
||||
- divergence = an early-warning score (0-100, high = fragile): the benchmark
|
||||
price rising *while* breadth falls, plus a nudge for already-low breadth.
|
||||
price holding/rising *while* breadth falls. Absolute low breadth stays in the
|
||||
State index so it is not counted twice.
|
||||
|
||||
This module only *computes* the indicator. It is deliberately NOT wired into the
|
||||
live regime index yet — the event study measures whether it actually leads before
|
||||
it earns any weight.
|
||||
The live monitor uses the breadth level in State and the pure divergence in
|
||||
Warning. The event study evaluates the latter chronologically.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,6 +25,7 @@ from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.ticker import Ticker
|
||||
from app.services import ticker_service
|
||||
from app.services.price_service import query_ohlcv
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -31,9 +33,9 @@ logger = logging.getLogger(__name__)
|
||||
Series = list[tuple[date, float]]
|
||||
|
||||
|
||||
def _breadth_from_closes(
|
||||
def _breadth_with_counts(
|
||||
closes_by_symbol: dict[str, Series], window: int = 200, min_tickers: int = 20
|
||||
) -> dict[date, float]:
|
||||
) -> tuple[dict[date, float], dict[date, int]]:
|
||||
"""Pure core: % of symbols above their own rolling SMA(window), per date.
|
||||
|
||||
Each symbol's SMA is computed once with a sliding sum (O(bars)); dates with
|
||||
@@ -55,11 +57,31 @@ def _breadth_from_closes(
|
||||
entry[1] += 1
|
||||
if closes[i] > sma:
|
||||
entry[0] += 1
|
||||
return {
|
||||
values = {
|
||||
d: round(above / total * 100.0, 2)
|
||||
for d, (above, total) in counts.items()
|
||||
if total >= min_tickers
|
||||
}
|
||||
eligible = {d: total for d, (_, total) in counts.items() if total >= min_tickers}
|
||||
return values, eligible
|
||||
|
||||
|
||||
def _breadth_from_closes(
|
||||
closes_by_symbol: dict[str, Series], window: int = 200, min_tickers: int = 20
|
||||
) -> dict[date, float]:
|
||||
"""Compatibility wrapper returning only the breadth percentage series."""
|
||||
return _breadth_with_counts(closes_by_symbol, window, min_tickers)[0]
|
||||
|
||||
|
||||
# Breadth deterioration counts fully when price masks it (true divergence, the
|
||||
# dangerous pre-top case) and at CONFIRMED_FLOOR when price falls with it.
|
||||
# v2 used a hard ``price_ret >= 0`` cliff, which zeroed the sensor during every
|
||||
# decline -- so on 2026-07-24, with the basket shedding 10 percentage points
|
||||
# above their 200-DMA in 20 sessions, Warning read exactly 0. Breadth *level*
|
||||
# lives in State but breadth *velocity* appears nowhere else, so partial credit
|
||||
# here is not double counting.
|
||||
DIVERGENCE_CONFIRMED_FLOOR = 0.35
|
||||
DIVERGENCE_TAPER_PCT = 3.0
|
||||
|
||||
|
||||
def compute_divergence_series(
|
||||
@@ -67,10 +89,9 @@ def compute_divergence_series(
|
||||
) -> dict[date, float]:
|
||||
"""Early-warning score (0-100, high = fragile) per date.
|
||||
|
||||
Fragility rises when the benchmark price climbs over ``lookback`` days while
|
||||
breadth deteriorates over the same window, and is nudged up when the absolute
|
||||
breadth level is already low. It is the *divergence* (not the level) that
|
||||
makes this leading.
|
||||
A 20 percentage-point breadth deterioration maps to 100 when the benchmark
|
||||
is flat or rising, tapering to ``DIVERGENCE_CONFIRMED_FLOOR`` of that once
|
||||
the benchmark is down ``DIVERGENCE_TAPER_PCT`` or more over the window.
|
||||
"""
|
||||
bench = {d: c for d, c in benchmark_closes}
|
||||
common = sorted(d for d in bench if d in breadth)
|
||||
@@ -82,14 +103,20 @@ def compute_divergence_series(
|
||||
continue
|
||||
price_ret = (bench[d] / price_past - 1.0) * 100.0 # %
|
||||
breadth_chg = breadth[d] - breadth[d0] # percentage points
|
||||
raw = price_ret - breadth_chg # price up & breadth down -> large
|
||||
score = 50.0 + raw * 2.0 + (50.0 - breadth[d]) * 0.4
|
||||
out[d] = max(0.0, min(100.0, round(score, 2)))
|
||||
deterioration = max(0.0, -breadth_chg)
|
||||
taper = max(0.0, min(1.0, (price_ret + DIVERGENCE_TAPER_PCT) / DIVERGENCE_TAPER_PCT))
|
||||
gate = DIVERGENCE_CONFIRMED_FLOOR + (1.0 - DIVERGENCE_CONFIRMED_FLOOR) * taper
|
||||
out[d] = max(0.0, min(100.0, round(deterioration * 5.0 * gate, 2)))
|
||||
return out
|
||||
|
||||
|
||||
async def _load_universe_closes(db: AsyncSession) -> dict[str, Series]:
|
||||
result = await db.execute(select(Ticker).order_by(Ticker.symbol))
|
||||
async def _load_universe_closes(
|
||||
db: AsyncSession, symbols: list[str] | None = None
|
||||
) -> dict[str, Series]:
|
||||
stmt = ticker_service.active_only(select(Ticker).order_by(Ticker.symbol))
|
||||
if symbols is not None:
|
||||
stmt = stmt.where(Ticker.symbol.in_(symbols))
|
||||
result = await db.execute(stmt)
|
||||
closes_by_symbol: dict[str, Series] = {}
|
||||
for ticker in result.scalars().all():
|
||||
try:
|
||||
@@ -103,16 +130,22 @@ async def _load_universe_closes(db: AsyncSession) -> dict[str, Series]:
|
||||
|
||||
|
||||
async def compute_breadth_series(
|
||||
db: AsyncSession, window: int = 200, min_tickers: int = 20
|
||||
db: AsyncSession,
|
||||
window: int = 200,
|
||||
min_tickers: int = 20,
|
||||
symbols: list[str] | None = None,
|
||||
) -> dict[date, float]:
|
||||
"""Historical breadth series across the stored universe (for the event study)."""
|
||||
closes_by_symbol = await _load_universe_closes(db)
|
||||
"""Historical breadth series across an explicit basket (or all stored names)."""
|
||||
closes_by_symbol = await _load_universe_closes(db, symbols)
|
||||
return _breadth_from_closes(closes_by_symbol, window, min_tickers)
|
||||
|
||||
|
||||
async def compute_breadth_today(db: AsyncSession) -> float | None:
|
||||
"""Latest breadth reading (thin wrapper, for future live use)."""
|
||||
series = await compute_breadth_series(db)
|
||||
if not series:
|
||||
return None
|
||||
return series[max(series)]
|
||||
async def compute_breadth_details(
|
||||
db: AsyncSession,
|
||||
symbols: list[str],
|
||||
window: int = 200,
|
||||
min_tickers: int = 20,
|
||||
) -> tuple[dict[date, float], dict[date, int]]:
|
||||
"""Breadth values plus the qualifying-member count for snapshot metadata."""
|
||||
closes_by_symbol = await _load_universe_closes(db, symbols)
|
||||
return _breadth_with_counts(closes_by_symbol, window, min_tickers)
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
"""Source-agnostic batch import framework (Dolt/SEC bulk data → PostgreSQL).
|
||||
|
||||
Every bulk importer (SEC facts, Dolt earnings, later Dolt stocks) plugs into
|
||||
``run_import`` and gets, for free, the plan's non-negotiables:
|
||||
|
||||
- **One run per source at a time** — a Postgres *session-level* advisory lock
|
||||
keyed by source. It is held on a single pinned connection for the whole run,
|
||||
so it survives the intermediate commits (the ``running`` row, then the
|
||||
promotion) and only releases at the end. No-op on non-Postgres (tests).
|
||||
- **Idempotent per revision** — the cheap ``detect_revision`` probe is compared
|
||||
against the last *promoted* run; an unchanged revision records a ``no_op``
|
||||
with **zero row changes** (no expensive fetch, no writes).
|
||||
- **Staging then atomic promotion** — the importer stages into an in-memory
|
||||
object (no physical staging tables), validation reads it, and only a passing
|
||||
run calls ``promote`` whose writes commit together with the run-row flip to
|
||||
``promoted`` in a single transaction.
|
||||
- **Failure is inert** — a failed validation or a mid-run exception marks the
|
||||
run ``failed``, alerts via the system-events path, and leaves the live tables
|
||||
exactly as they were (nothing is written before ``promote``).
|
||||
|
||||
Every attempt — promoted, no_op, or failed — is recorded in ``data_import_runs``.
|
||||
KISS: no conflicts table (summaries go in ``validation_json``), no revision
|
||||
table (idempotency queries the last run), no aggregate tables.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Any, Protocol, runtime_checkable
|
||||
|
||||
from sqlalchemy import exists, select, text
|
||||
from sqlalchemy.engine import Engine # noqa: F401 (typing only)
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
|
||||
|
||||
from app.database import engine as app_engine
|
||||
from app.models.data_import_run import DataImportRun
|
||||
from app.services import system_event_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# data_import_runs.status values
|
||||
STATUS_RUNNING = "running"
|
||||
STATUS_VALIDATED = "validated"
|
||||
STATUS_PROMOTED = "promoted"
|
||||
STATUS_NO_OP = "no_op"
|
||||
STATUS_DEFERRED = "deferred"
|
||||
STATUS_FAILED = "failed"
|
||||
|
||||
_MAX_ERROR_LEN = 4000
|
||||
|
||||
|
||||
@dataclass
|
||||
class ValidationResult:
|
||||
"""Outcome of an importer's validation gates.
|
||||
|
||||
``summary`` is serialized into ``validation_json`` (reconciliation /
|
||||
discrepancy details live here — no separate conflicts table). ``validate``
|
||||
MUST be read-only: it reads the staged object and, if needed, live tables
|
||||
for comparison, but writes nothing — that invariant is what makes a failed
|
||||
run leave the dataset untouched.
|
||||
"""
|
||||
|
||||
ok: bool
|
||||
summary: dict[str, Any] = field(default_factory=dict)
|
||||
source_max_date: date | None = None
|
||||
messages: list[str] = field(default_factory=list)
|
||||
# Expected source-side lag: retry without an immediate error alert. Sources
|
||||
# can bound the quiet period with deferred_alert_after_days. Only meaningful
|
||||
# when ok=False.
|
||||
retryable: bool = False
|
||||
deferred_alert_after_days: int | None = None
|
||||
deferred_alert_messages: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SourceImporter(Protocol):
|
||||
"""Interface a concrete bulk importer implements. All methods receive the
|
||||
session bound to the lock-holding connection; ``stage`` and ``validate``
|
||||
never write to live tables, only ``promote`` does."""
|
||||
|
||||
source: str # sec_facts | dolt_earnings | dolt_stocks
|
||||
|
||||
async def detect_revision(self, db: AsyncSession) -> str | None:
|
||||
"""Cheap probe of the source revision (Dolt commit / SEC archive SHA).
|
||||
|
||||
Returns the revision id, or None when it can't be determined cheaply
|
||||
(in which case idempotency is skipped and the run always stages)."""
|
||||
...
|
||||
|
||||
async def stage(self, db: AsyncSession) -> Any:
|
||||
"""Download/parse into an in-memory staged representation. No writes to
|
||||
live tables."""
|
||||
...
|
||||
|
||||
async def validate(self, db: AsyncSession, staged: Any) -> ValidationResult:
|
||||
"""Run the source's validation gates against ``staged``. Read-only."""
|
||||
...
|
||||
|
||||
async def promote(self, db: AsyncSession, staged: Any, run_id: int) -> dict[str, int]:
|
||||
"""Apply ``staged`` to the live tables. Called inside the promotion
|
||||
transaction; the caller commits. ``run_id`` is the current
|
||||
``data_import_runs.id`` so written rows can be stamped with their
|
||||
``import_run_id``. Returns row-count deltas."""
|
||||
...
|
||||
|
||||
|
||||
def _advisory_key(source: str) -> int:
|
||||
"""Deterministic signed 64-bit key for a source's advisory lock."""
|
||||
digest = hashlib.blake2b(source.encode("utf-8"), digest_size=8).digest()
|
||||
return int.from_bytes(digest, "big", signed=True)
|
||||
|
||||
|
||||
async def _last_promoted_revision(db: AsyncSession, source: str) -> str | None:
|
||||
"""Revision of the most recent *promoted* run for ``source`` (the revision
|
||||
currently loaded), or None if none has promoted yet."""
|
||||
row = await db.execute(
|
||||
select(DataImportRun.revision)
|
||||
.where(
|
||||
DataImportRun.source == source,
|
||||
DataImportRun.status == STATUS_PROMOTED,
|
||||
)
|
||||
.order_by(DataImportRun.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
return row.scalar_one_or_none()
|
||||
|
||||
|
||||
async def _promotion_state_since(
|
||||
db: AsyncSession, source: str, cutoff: datetime
|
||||
) -> str:
|
||||
promoted = (
|
||||
DataImportRun.source == source,
|
||||
DataImportRun.status == STATUS_PROMOTED,
|
||||
)
|
||||
ever, recent = (
|
||||
await db.execute(
|
||||
select(
|
||||
exists().where(*promoted),
|
||||
exists().where(*promoted, DataImportRun.started_at >= cutoff),
|
||||
)
|
||||
)
|
||||
).one()
|
||||
return "recent" if recent else "stale" if ever else "never"
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
async def _alert(
|
||||
db: AsyncSession,
|
||||
source: str,
|
||||
code: str,
|
||||
messages: list[str],
|
||||
*,
|
||||
severity: str = "error",
|
||||
dedup_hours: int = 24,
|
||||
) -> None:
|
||||
try:
|
||||
await system_event_service.log_event(
|
||||
db,
|
||||
severity=severity,
|
||||
source="data_import",
|
||||
code=f"{source}_{code}",
|
||||
message=(("; ".join(messages)) or code)[:_MAX_ERROR_LEN],
|
||||
dedup_key=f"data_import:{source}:{code}",
|
||||
dedup_hours=dedup_hours,
|
||||
)
|
||||
except Exception: # noqa: BLE001 — alerting must never mask the real outcome
|
||||
logger.exception("Failed to emit data_import alert %s/%s", source, code)
|
||||
|
||||
|
||||
async def run_import(
|
||||
importer: SourceImporter,
|
||||
*,
|
||||
engine: AsyncEngine | None = None,
|
||||
force: bool = False,
|
||||
) -> DataImportRun | None:
|
||||
"""Run one import for ``importer``.
|
||||
|
||||
Returns the recorded ``DataImportRun`` (promoted / no_op / deferred /
|
||||
failed), or None
|
||||
when the per-source advisory lock is already held (another run is active).
|
||||
|
||||
``force`` runs even when the revision is unchanged. The revision tracks the
|
||||
*source*, so a re-import driven by a change on our side — a parser fix that
|
||||
makes stored rows stale — is a no_op under the normal gate. Manually invoked
|
||||
only; scheduled jobs must leave it False so an unchanged source stays a no_op.
|
||||
"""
|
||||
engine = engine or app_engine
|
||||
source = importer.source
|
||||
is_pg = engine.dialect.name == "postgresql"
|
||||
key = _advisory_key(source)
|
||||
|
||||
async with engine.connect() as conn:
|
||||
# Bind the session to this one connection so the session-level advisory
|
||||
# lock persists across our commits. expire_on_commit must be set here —
|
||||
# the app factory's setting doesn't carry to a directly-built session.
|
||||
session = AsyncSession(bind=conn, expire_on_commit=False)
|
||||
try:
|
||||
if is_pg:
|
||||
got = (
|
||||
await session.execute(
|
||||
text("SELECT pg_try_advisory_lock(:k)"), {"k": key}
|
||||
)
|
||||
).scalar()
|
||||
await session.commit()
|
||||
if not got:
|
||||
logger.info("data_import %s: lock held, skipping", source)
|
||||
return None
|
||||
|
||||
# Record the attempt FIRST — before the external revision probe, the
|
||||
# most likely failure — so anything below is recorded and alerted and
|
||||
# never escapes unrecorded. Revision is filled in once detected.
|
||||
run = DataImportRun(
|
||||
source=source,
|
||||
status=STATUS_RUNNING,
|
||||
started_at=_now(),
|
||||
)
|
||||
session.add(run)
|
||||
await session.commit()
|
||||
await session.refresh(run)
|
||||
|
||||
try:
|
||||
revision = await importer.detect_revision(session)
|
||||
run.revision = revision
|
||||
last_rev = await _last_promoted_revision(session, source)
|
||||
if not force and revision is not None and revision == last_rev:
|
||||
run.status = STATUS_NO_OP
|
||||
run.completed_at = _now()
|
||||
await session.commit()
|
||||
logger.info("data_import %s: no_op (revision %s)", source, revision)
|
||||
return run
|
||||
|
||||
staged = await importer.stage(session)
|
||||
result = await importer.validate(session, staged)
|
||||
run.source_max_date = result.source_max_date
|
||||
run.validation_json = json.dumps(result.summary, default=str)
|
||||
|
||||
if not result.ok:
|
||||
run.error_details = ("; ".join(result.messages))[:_MAX_ERROR_LEN]
|
||||
run.completed_at = _now()
|
||||
if result.retryable:
|
||||
run.status = STATUS_DEFERRED
|
||||
await session.commit()
|
||||
alert_days = result.deferred_alert_after_days
|
||||
if alert_days is not None:
|
||||
alert_days = max(1, alert_days)
|
||||
cutoff = run.started_at - timedelta(days=alert_days)
|
||||
promotion_state = await _promotion_state_since(
|
||||
session, source, cutoff
|
||||
)
|
||||
if promotion_state != "recent":
|
||||
history = (
|
||||
f"{source} import has never promoted successfully"
|
||||
if promotion_state == "never"
|
||||
else f"{source} import has not promoted successfully "
|
||||
f"within {alert_days} day(s)"
|
||||
)
|
||||
await _alert(
|
||||
session,
|
||||
source,
|
||||
"deferred_stale",
|
||||
[
|
||||
f"{history}; import remains deferred",
|
||||
*result.deferred_alert_messages,
|
||||
f"Current deferral: "
|
||||
f"{run.error_details or 'validation deferred'}",
|
||||
],
|
||||
severity="warning",
|
||||
dedup_hours=alert_days * 24,
|
||||
)
|
||||
logger.info(
|
||||
"data_import %s: deferred for retry: %s",
|
||||
source,
|
||||
result.messages,
|
||||
)
|
||||
return run
|
||||
|
||||
run.status = STATUS_FAILED
|
||||
await session.commit()
|
||||
await _alert(session, source, "validation_failed", result.messages)
|
||||
logger.warning(
|
||||
"data_import %s: validation failed: %s",
|
||||
source,
|
||||
result.messages,
|
||||
)
|
||||
return run
|
||||
|
||||
# Promotion: importer writes + run-row flip in one transaction.
|
||||
row_counts = await importer.promote(session, staged, run.id)
|
||||
run.status = STATUS_PROMOTED
|
||||
run.row_counts_json = json.dumps(row_counts, default=str)
|
||||
run.completed_at = _now()
|
||||
await session.commit()
|
||||
await session.refresh(run)
|
||||
logger.info(
|
||||
"data_import %s: promoted (revision %s, rows %s)",
|
||||
source,
|
||||
revision,
|
||||
row_counts,
|
||||
)
|
||||
return run
|
||||
|
||||
except asyncio.CancelledError:
|
||||
# Deploy / scheduler shutdown: best-effort mark failed so no
|
||||
# ``running`` row lingers, then let the cancellation propagate —
|
||||
# never swallow it.
|
||||
try:
|
||||
await session.rollback()
|
||||
run.status = STATUS_FAILED
|
||||
run.error_details = "cancelled"
|
||||
run.completed_at = _now()
|
||||
await session.commit()
|
||||
except BaseException: # noqa: BLE001 — best-effort during teardown
|
||||
logger.warning(
|
||||
"data_import %s: could not record cancellation", source
|
||||
)
|
||||
raise
|
||||
|
||||
except Exception as exc: # noqa: BLE001 — record + alert, don't crash the job
|
||||
await session.rollback()
|
||||
run.status = STATUS_FAILED
|
||||
run.error_details = repr(exc)[:_MAX_ERROR_LEN]
|
||||
run.completed_at = _now()
|
||||
try:
|
||||
await session.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("data_import %s: failed to record failure", source)
|
||||
await _alert(session, source, "import_error", [repr(exc)])
|
||||
logger.exception("data_import %s: import error", source)
|
||||
return run
|
||||
|
||||
finally:
|
||||
if is_pg:
|
||||
try:
|
||||
await session.execute(
|
||||
text("SELECT pg_advisory_unlock(:k)"), {"k": key}
|
||||
)
|
||||
await session.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("data_import %s: failed to release lock", source)
|
||||
await session.close()
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Minimal async client for a local Dolt clone.
|
||||
|
||||
The application never runs a long-lived Dolt sql-server; it shells out to the
|
||||
`dolt` CLI against a persistent clone and reads results as CSV. Every call goes
|
||||
through ``asyncio.create_subprocess_exec`` because the scheduler shares one event
|
||||
loop with the API (`app/scheduler.py:73`) — a blocking `subprocess.run` here
|
||||
would stall request handling.
|
||||
|
||||
Production keeps the clone in ``DOLT_DATA_DIR`` outside the deploy tree; the
|
||||
binary path and data dir are configured (see ``app/config.py``). Read via
|
||||
``dolt sql -r csv``; refresh with ``pull`` and record the resulting commit hash
|
||||
as the import revision.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import csv
|
||||
import io
|
||||
import logging
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Default subprocess timeout. A hung `dolt pull`/`sql` would otherwise pin the
|
||||
# import's connection and its advisory lock indefinitely, so every call is
|
||||
# bounded; callers may override per operation.
|
||||
DEFAULT_TIMEOUT = 600.0
|
||||
|
||||
|
||||
class DoltError(RuntimeError):
|
||||
"""A dolt subprocess failed, timed out, or exited non-zero."""
|
||||
|
||||
|
||||
async def _run(
|
||||
binary: str, args: list[str], *, cwd: Path, timeout: float = DEFAULT_TIMEOUT
|
||||
) -> str:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
binary,
|
||||
*args,
|
||||
cwd=str(cwd),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
try:
|
||||
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
proc.kill()
|
||||
try:
|
||||
await proc.wait()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
raise DoltError(f"dolt {args[0] if args else ''} timed out after {timeout:.0f}s")
|
||||
if proc.returncode != 0:
|
||||
raise DoltError(
|
||||
f"dolt {' '.join(args)} failed ({proc.returncode}): "
|
||||
f"{stderr.decode('utf-8', 'replace').strip()[:500]}"
|
||||
)
|
||||
return stdout.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def ensure_free_disk(path: Path, min_free_gb: float) -> None:
|
||||
"""Raise if free space at ``path`` is below the threshold (checked before a
|
||||
pull that could grow the clone). Uses the nearest existing ancestor so it
|
||||
works before the clone dir exists."""
|
||||
probe = path
|
||||
while not probe.exists() and probe.parent != probe:
|
||||
probe = probe.parent
|
||||
free_gb = shutil.disk_usage(probe).free / (1024**3)
|
||||
if free_gb < min_free_gb:
|
||||
raise DoltError(
|
||||
f"insufficient disk for dolt at {path}: {free_gb:.1f} GB free "
|
||||
f"< {min_free_gb:.1f} GB required"
|
||||
)
|
||||
|
||||
|
||||
async def pull(repo_dir: Path, *, binary: str, timeout: float = DEFAULT_TIMEOUT) -> None:
|
||||
"""`dolt pull` the persistent clone to the latest upstream revision."""
|
||||
await _run(binary, ["pull"], cwd=repo_dir, timeout=timeout)
|
||||
|
||||
|
||||
async def current_commit(
|
||||
repo_dir: Path, *, binary: str, timeout: float = DEFAULT_TIMEOUT
|
||||
) -> str:
|
||||
"""The HEAD commit hash of the clone — used as the import revision.
|
||||
|
||||
Uses ``DOLT_HASHOF('HEAD')`` (which formally identifies HEAD) rather than
|
||||
ordering ``dolt_log`` by timestamp."""
|
||||
rows = await query_csv(
|
||||
repo_dir, "SELECT DOLT_HASHOF('HEAD') AS commit_hash", binary=binary, timeout=timeout
|
||||
)
|
||||
if not rows or not rows[0].get("commit_hash"):
|
||||
raise DoltError("could not read HEAD commit hash")
|
||||
return rows[0]["commit_hash"]
|
||||
|
||||
|
||||
async def query_csv(
|
||||
repo_dir: Path, sql: str, *, binary: str, timeout: float = DEFAULT_TIMEOUT
|
||||
) -> list[dict[str, str]]:
|
||||
"""Run a read query and parse the CSV result into a list of dict rows."""
|
||||
out = await _run(binary, ["sql", "-q", sql, "-r", "csv"], cwd=repo_dir, timeout=timeout)
|
||||
if not out.strip():
|
||||
return []
|
||||
return list(csv.DictReader(io.StringIO(out)))
|
||||
@@ -0,0 +1,361 @@
|
||||
"""Production importer for the DoltHub post-no-preference/earnings calendar.
|
||||
|
||||
A ``SourceImporter`` (see ``app/services/data_import.py``) that pulls the local
|
||||
Dolt clone, aligns the announcement calendar to the EPS history with the pure DP
|
||||
in ``earnings_alignment`` (reused from the research script, not extending it),
|
||||
and writes ``earnings_events`` for the tracked universe.
|
||||
|
||||
Shadow by construction: nothing reads ``earnings_events`` until the API/panel
|
||||
lands (A4), so writing it does not touch production behavior.
|
||||
|
||||
**Promotion is destructive** — future-dated rows for this source are deleted and
|
||||
re-inserted every run so reschedules/cancellations never linger. The forward
|
||||
calendar is the project's acceptance gate, so ``validate`` is fail-closed: it
|
||||
blocks promotion when the staged future set is empty or has collapsed relative
|
||||
to what's already loaded.
|
||||
|
||||
Attribution: the earnings data is CC BY-SA 4.0 from post-no-preference/earnings.
|
||||
See the repo ``NOTICE``. Internal use only — no redistribution.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import case, delete, func, select
|
||||
|
||||
from app.config import settings
|
||||
from app.database import insert_for_session
|
||||
from app.models.earnings_event import EarningsEvent
|
||||
from app.models.ticker import Ticker
|
||||
from app.services import dolt_client, earnings_alignment, ticker_service
|
||||
from app.services.data_import import ValidationResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SOURCE = "dolt_earnings"
|
||||
|
||||
# Earliest announcement date to import (matches the research backfill window).
|
||||
WINDOW_START = date(2020, 1, 22)
|
||||
# Alignment tolerances (research defaults): an announcement may lead its period
|
||||
# end by up to 14 days or lag it by up to 90.
|
||||
MAX_LAG_DAYS = 90
|
||||
MAX_LEAD_DAYS = 14
|
||||
# Fail promotion if the staged forward calendar drops below this fraction of the
|
||||
# currently-loaded forward calendar (guards the destructive re-insert against a
|
||||
# partial parse / symbol-mapping regression).
|
||||
MIN_FUTURE_RATIO = 0.5
|
||||
# Initial-load gates (when nothing is loaded yet — the ratio gate has no baseline).
|
||||
# The source publishes a forward calendar; require a real horizon, not one stray
|
||||
# future row. 21 days is a conservative floor under the ~35d horizon observed on
|
||||
# the live clone.
|
||||
MIN_FORWARD_HORIZON_DAYS = 21
|
||||
# ...and require the symbol join to reach most of the tracked universe, so a
|
||||
# broken/normalization-dropped join can't seed a hollow calendar.
|
||||
MIN_INITIAL_COVERAGE = 0.5
|
||||
|
||||
_CAL_SQL = (
|
||||
"SELECT act_symbol, `date`, `when` FROM earnings_calendar "
|
||||
f"WHERE `date` >= '{WINDOW_START.isoformat()}'"
|
||||
)
|
||||
_HIST_SQL = (
|
||||
"SELECT act_symbol, period_end_date, reported, estimate FROM eps_history "
|
||||
f"WHERE period_end_date >= '{(WINDOW_START.replace(year=WINDOW_START.year - 1)).isoformat()}'"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class StagedEarnings:
|
||||
rows: list[dict[str, Any]]
|
||||
stats: dict[str, Any] = field(default_factory=dict)
|
||||
future_count: int = 0
|
||||
max_announce_date: date | None = None
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class DoltEarningsImporter:
|
||||
source = SOURCE
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
repo_dir: Path | str | None = None,
|
||||
binary: str | None = None,
|
||||
today: date | None = None,
|
||||
do_pull: bool = True,
|
||||
dolt: Any = dolt_client,
|
||||
) -> None:
|
||||
self.repo_dir = Path(
|
||||
repo_dir
|
||||
or (Path(settings.dolt_data_dir) / settings.dolt_earnings_subdir)
|
||||
)
|
||||
self.binary = binary or settings.dolt_binary
|
||||
self.today = today or _now().date()
|
||||
self.do_pull = do_pull
|
||||
self._dolt = dolt # injectable for tests
|
||||
|
||||
# -- SourceImporter protocol -------------------------------------------
|
||||
|
||||
async def detect_revision(self, db) -> str | None:
|
||||
timeout = settings.dolt_command_timeout_seconds
|
||||
if self.do_pull:
|
||||
dolt_client.ensure_free_disk(self.repo_dir, settings.dolt_min_free_disk_gb)
|
||||
await self._dolt.pull(self.repo_dir, binary=self.binary, timeout=timeout)
|
||||
return await self._dolt.current_commit(
|
||||
self.repo_dir, binary=self.binary, timeout=timeout
|
||||
)
|
||||
|
||||
async def stage(self, db) -> StagedEarnings:
|
||||
universe = await self._load_universe(db) # {normalised symbol: ticker_id}
|
||||
|
||||
timeout = settings.dolt_command_timeout_seconds
|
||||
cal_raw = await self._dolt.query_csv(
|
||||
self.repo_dir, _CAL_SQL, binary=self.binary, timeout=timeout
|
||||
)
|
||||
hist_raw = await self._dolt.query_csv(
|
||||
self.repo_dir, _HIST_SQL, binary=self.binary, timeout=timeout
|
||||
)
|
||||
_require_columns(cal_raw, {"act_symbol", "date", "when"}, "earnings_calendar")
|
||||
_require_columns(
|
||||
hist_raw, {"act_symbol", "period_end_date", "reported", "estimate"}, "eps_history"
|
||||
)
|
||||
|
||||
cal_parsed = _parse_calendar(cal_raw, universe)
|
||||
hist_parsed = _parse_history(hist_raw, universe)
|
||||
calendar, cal_stats = earnings_alignment.dedup_calendar(cal_parsed)
|
||||
history, hist_stats = earnings_alignment.dedup_history(hist_parsed)
|
||||
|
||||
period_lower = WINDOW_START.replace(year=WINDOW_START.year - 1)
|
||||
rows: list[dict[str, Any]] = []
|
||||
matched = unmatched = 0
|
||||
for symbol, events in calendar.items():
|
||||
ticker_id = universe[symbol]
|
||||
periods = [
|
||||
p for p in history.get(symbol, []) if p["period_end_date"] >= period_lower
|
||||
]
|
||||
matches, unmatched_events, _ = earnings_alignment.align_symbol(
|
||||
events, periods, max_lag_days=MAX_LAG_DAYS, max_lead_days=MAX_LEAD_DAYS
|
||||
)
|
||||
matched += len(matches)
|
||||
unmatched += len(unmatched_events)
|
||||
matched_by_event = {e: p for e, p in matches}
|
||||
for e_idx, event in enumerate(events):
|
||||
p_idx = matched_by_event.get(e_idx)
|
||||
period = periods[p_idx] if p_idx is not None else None
|
||||
rows.append(
|
||||
{
|
||||
"ticker_id": ticker_id,
|
||||
"symbol": symbol,
|
||||
"announce_date": event["announce_date"],
|
||||
"session": event["session"],
|
||||
"period_end": period["period_end_date"] if period else None,
|
||||
"eps_estimate": period["eps_estimate"] if period else None,
|
||||
"eps_actual": period["eps_actual"] if period else None,
|
||||
}
|
||||
)
|
||||
|
||||
future_rows = [r for r in rows if r["announce_date"] > self.today]
|
||||
tickers_with_future = {r["ticker_id"] for r in future_rows}
|
||||
stats = {
|
||||
"calendar": cal_stats,
|
||||
"eps_history": hist_stats,
|
||||
"universe_size": len(universe),
|
||||
"symbols_with_calendar": len(calendar),
|
||||
"matched_events": matched,
|
||||
"unmatched_events": unmatched,
|
||||
"tracked_tickers_with_future_date": len(tickers_with_future),
|
||||
}
|
||||
return StagedEarnings(
|
||||
rows=rows,
|
||||
stats=stats,
|
||||
future_count=len(future_rows),
|
||||
max_announce_date=max((r["announce_date"] for r in rows), default=None),
|
||||
)
|
||||
|
||||
async def validate(self, db, staged: StagedEarnings) -> ValidationResult:
|
||||
# Promote deletes+reinserts the forward calendar, so this gate is
|
||||
# fail-closed. The forward calendar is the project's acceptance gate.
|
||||
messages: list[str] = []
|
||||
current_future = await self._current_future_count(db)
|
||||
universe_size = int(staged.stats.get("universe_size", 0) or 0)
|
||||
coverage = (
|
||||
staged.stats.get("symbols_with_calendar", 0) / universe_size
|
||||
if universe_size
|
||||
else 0.0
|
||||
)
|
||||
horizon_days = (
|
||||
(staged.max_announce_date - self.today).days if staged.max_announce_date else 0
|
||||
)
|
||||
|
||||
if staged.future_count == 0:
|
||||
messages.append("no future-dated earnings rows staged")
|
||||
elif current_future == 0:
|
||||
# Initial load: no baseline for the ratio gate, so require a real
|
||||
# forward horizon and broad universe coverage instead of one stray row.
|
||||
if horizon_days < MIN_FORWARD_HORIZON_DAYS:
|
||||
messages.append(
|
||||
f"forward horizon only {horizon_days}d < {MIN_FORWARD_HORIZON_DAYS}d "
|
||||
"on initial load"
|
||||
)
|
||||
if coverage < MIN_INITIAL_COVERAGE:
|
||||
messages.append(
|
||||
f"initial universe coverage {coverage:.0%} "
|
||||
f"< {MIN_INITIAL_COVERAGE:.0%} — symbol join likely broken"
|
||||
)
|
||||
elif staged.future_count < current_future * MIN_FUTURE_RATIO:
|
||||
messages.append(
|
||||
f"forward calendar collapsed: staged {staged.future_count} future rows "
|
||||
f"< {MIN_FUTURE_RATIO:.0%} of current {current_future}"
|
||||
)
|
||||
|
||||
keys = [(r["ticker_id"], r["announce_date"]) for r in staged.rows]
|
||||
if len(keys) != len(set(keys)):
|
||||
messages.append("duplicate (ticker_id, announce_date) in staged set")
|
||||
|
||||
summary = {
|
||||
**staged.stats,
|
||||
"staged_rows": len(staged.rows),
|
||||
"future_rows": staged.future_count,
|
||||
"current_future_rows": current_future,
|
||||
"forward_horizon_days": horizon_days,
|
||||
"universe_coverage": round(coverage, 3),
|
||||
}
|
||||
return ValidationResult(
|
||||
ok=not messages,
|
||||
summary=summary,
|
||||
source_max_date=staged.max_announce_date,
|
||||
messages=messages,
|
||||
)
|
||||
|
||||
async def promote(self, db, staged: StagedEarnings, run_id: int) -> dict[str, int]:
|
||||
# Rescheduling: drop this source's future rows, then upsert the staged
|
||||
# set. Past rows (results) are never deleted; moved/cancelled future
|
||||
# dates simply don't reappear.
|
||||
deleted = (
|
||||
await db.execute(
|
||||
delete(EarningsEvent).where(
|
||||
EarningsEvent.source == SOURCE,
|
||||
EarningsEvent.announce_date > self.today,
|
||||
)
|
||||
)
|
||||
).rowcount or 0
|
||||
|
||||
now = _now()
|
||||
for r in staged.rows:
|
||||
stmt = insert_for_session(db, EarningsEvent).values(
|
||||
ticker_id=r["ticker_id"],
|
||||
announce_date=r["announce_date"],
|
||||
session=r["session"],
|
||||
period_end=r["period_end"],
|
||||
eps_estimate=r["eps_estimate"],
|
||||
eps_actual=r["eps_actual"],
|
||||
source=SOURCE,
|
||||
import_run_id=run_id,
|
||||
created_at=now,
|
||||
)
|
||||
# Preserve a non-null prior EPS/period-end if a re-pairing comes back
|
||||
# null; prefer a known session over 'unknown'.
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=["ticker_id", "announce_date"],
|
||||
set_={
|
||||
"session": case(
|
||||
(stmt.excluded.session != "unknown", stmt.excluded.session),
|
||||
else_=EarningsEvent.session,
|
||||
),
|
||||
"period_end": func.coalesce(
|
||||
stmt.excluded.period_end, EarningsEvent.period_end
|
||||
),
|
||||
"eps_estimate": func.coalesce(
|
||||
stmt.excluded.eps_estimate, EarningsEvent.eps_estimate
|
||||
),
|
||||
"eps_actual": func.coalesce(
|
||||
stmt.excluded.eps_actual, EarningsEvent.eps_actual
|
||||
),
|
||||
"source": stmt.excluded.source,
|
||||
"import_run_id": stmt.excluded.import_run_id,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt)
|
||||
|
||||
return {"deleted_future": int(deleted), "upserted": len(staged.rows)}
|
||||
|
||||
# -- helpers -----------------------------------------------------------
|
||||
|
||||
async def _load_universe(self, db) -> dict[str, int]:
|
||||
rows = (
|
||||
await db.execute(
|
||||
ticker_service.active_only(select(Ticker.id, Ticker.symbol))
|
||||
)
|
||||
).all()
|
||||
return {
|
||||
earnings_alignment.normalise_symbol(symbol): tid
|
||||
for tid, symbol in rows
|
||||
if symbol
|
||||
}
|
||||
|
||||
async def _current_future_count(self, db) -> int:
|
||||
return (
|
||||
await db.execute(
|
||||
select(func.count())
|
||||
.select_from(EarningsEvent)
|
||||
.where(
|
||||
EarningsEvent.source == SOURCE,
|
||||
EarningsEvent.announce_date > self.today,
|
||||
)
|
||||
)
|
||||
).scalar_one()
|
||||
|
||||
|
||||
def _require_columns(rows: list[dict[str, str]], required: set[str], table: str) -> None:
|
||||
"""Upstream schema-change gate: a missing column stops the run (→ failed)."""
|
||||
if not rows:
|
||||
return
|
||||
present = set(rows[0].keys())
|
||||
missing = required - present
|
||||
if missing:
|
||||
raise ValueError(f"{table}: upstream schema change, missing columns {sorted(missing)}")
|
||||
|
||||
|
||||
def _parse_calendar(raw: list[dict[str, str]], universe: dict[str, int]) -> list[dict[str, Any]]:
|
||||
out: list[dict[str, Any]] = []
|
||||
for row in raw:
|
||||
symbol = earnings_alignment.normalise_symbol(row.get("act_symbol"))
|
||||
raw_date = str(row.get("date") or "")[:10]
|
||||
if symbol not in universe or not raw_date:
|
||||
continue
|
||||
announce_date = date.fromisoformat(raw_date)
|
||||
if announce_date < WINDOW_START:
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"symbol": symbol,
|
||||
"announce_date": announce_date,
|
||||
"session": earnings_alignment.normalise_session(row.get("when")),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _parse_history(raw: list[dict[str, str]], universe: dict[str, int]) -> list[dict[str, Any]]:
|
||||
out: list[dict[str, Any]] = []
|
||||
for row in raw:
|
||||
symbol = earnings_alignment.normalise_symbol(row.get("act_symbol"))
|
||||
raw_date = str(row.get("period_end_date") or "")[:10]
|
||||
if symbol not in universe or not raw_date:
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"symbol": symbol,
|
||||
"period_end_date": date.fromisoformat(raw_date),
|
||||
"eps_actual": earnings_alignment.safe_number(row.get("reported")),
|
||||
"eps_estimate": earnings_alignment.safe_number(row.get("estimate")),
|
||||
}
|
||||
)
|
||||
return out
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Pure calendar<->EPS-history alignment for the DoltHub earnings source.
|
||||
|
||||
The earnings repo keeps the announcement calendar (`earnings_calendar`) and the
|
||||
reported/estimate EPS history (`eps_history`) in separate tables with no shared
|
||||
key — the calendar has announce dates, the history has period-end dates. This
|
||||
module reproduces the research importer's **minimum-cost monotonic alignment**
|
||||
(`scripts/import_dolthub_earnings.py`) as pure, DB-free, unit-testable functions
|
||||
so the production importer can reuse it without extending that one-off script.
|
||||
|
||||
Constants and cost function are kept identical to the research script; the DP is
|
||||
what pairs each announcement with the quarter it reported, tolerating gaps on
|
||||
either side. Do not tune these without re-validating surprise-history pairing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections import defaultdict
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
# Alignment costs — identical to scripts/import_dolthub_earnings.py.
|
||||
SKIP_EVENT_COST = 45.0
|
||||
SKIP_PERIOD_COST = 45.0
|
||||
_TYPICAL_ANNOUNCE_LAG_DAYS = 30 # announcements land ~a month after period end
|
||||
_MISSING_SESSION_PENALTY = 3.0
|
||||
|
||||
# Session normalization → the three values the schema/API promise.
|
||||
_SESSION_ALIASES = {
|
||||
"before market open": "bmo",
|
||||
"before open": "bmo",
|
||||
"bmo": "bmo",
|
||||
"after market close": "amc",
|
||||
"after close": "amc",
|
||||
"amc": "amc",
|
||||
}
|
||||
|
||||
|
||||
def normalise_symbol(value: Any) -> str:
|
||||
"""Upper-case, trim, and map dots to dashes so the DoltHub `act_symbol`
|
||||
(`BF.B`) and the app's `tickers.symbol` join after the same normalization."""
|
||||
return str(value or "").strip().upper().replace(".", "-")
|
||||
|
||||
|
||||
def normalise_session(value: Any) -> str:
|
||||
"""Map the source `when` text to bmo | amc | unknown. Anything not clearly a
|
||||
pre-open or post-close session (including 'during market hours' and blanks)
|
||||
collapses to 'unknown' — the schema/API only promise those three."""
|
||||
cleaned = str(value or "").strip().lower().replace("_", " ").replace("-", " ")
|
||||
return _SESSION_ALIASES.get(cleaned, "unknown")
|
||||
|
||||
|
||||
def safe_number(value: Any) -> float | None:
|
||||
if value is None or str(value).strip() == "":
|
||||
return None
|
||||
try:
|
||||
result = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return result if math.isfinite(result) else None
|
||||
|
||||
|
||||
def dedup_calendar(
|
||||
rows: list[dict[str, Any]],
|
||||
) -> tuple[dict[str, list[dict[str, Any]]], dict[str, int]]:
|
||||
"""Collapse to one row per (symbol, announce_date), preferring a known
|
||||
session over 'unknown'. Rows must be pre-parsed:
|
||||
{symbol, announce_date: date, session}. Returns {symbol: [events sorted by
|
||||
date]} and dedup stats."""
|
||||
by_key: dict[tuple[str, date], dict[str, Any]] = {}
|
||||
duplicate_rows = 0
|
||||
restated_rows = 0
|
||||
for row in rows:
|
||||
key = (row["symbol"], row["announce_date"])
|
||||
previous = by_key.get(key)
|
||||
if previous is None:
|
||||
by_key[key] = row
|
||||
continue
|
||||
duplicate_rows += 1
|
||||
prev_known = previous["session"] != "unknown"
|
||||
new_known = row["session"] != "unknown"
|
||||
if prev_known and new_known and previous["session"] != row["session"]:
|
||||
restated_rows += 1
|
||||
# Prefer a row that carries a known session.
|
||||
if new_known:
|
||||
by_key[key] = row
|
||||
grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||||
for row in by_key.values():
|
||||
grouped[row["symbol"]].append(row)
|
||||
for events in grouped.values():
|
||||
events.sort(key=lambda item: item["announce_date"])
|
||||
return grouped, {
|
||||
"deduped_rows": len(by_key),
|
||||
"duplicate_rows": duplicate_rows,
|
||||
"restated_rows": restated_rows,
|
||||
}
|
||||
|
||||
|
||||
def dedup_history(
|
||||
rows: list[dict[str, Any]],
|
||||
) -> tuple[dict[str, list[dict[str, Any]]], dict[str, int]]:
|
||||
"""Collapse to one row per (symbol, period_end_date), preferring the row with
|
||||
more non-null EPS fields. Rows must be pre-parsed:
|
||||
{symbol, period_end_date: date, eps_actual, eps_estimate}."""
|
||||
fields = ("eps_actual", "eps_estimate")
|
||||
by_key: dict[tuple[str, date], dict[str, Any]] = {}
|
||||
duplicate_rows = 0
|
||||
restated_rows = 0
|
||||
for row in rows:
|
||||
key = (row["symbol"], row["period_end_date"])
|
||||
previous = by_key.get(key)
|
||||
if previous is None:
|
||||
by_key[key] = row
|
||||
continue
|
||||
duplicate_rows += 1
|
||||
if any(
|
||||
previous.get(f) is not None
|
||||
and row.get(f) is not None
|
||||
and previous[f] != row[f]
|
||||
for f in fields
|
||||
):
|
||||
restated_rows += 1
|
||||
prev_score = sum(previous.get(f) is not None for f in fields)
|
||||
new_score = sum(row.get(f) is not None for f in fields)
|
||||
if new_score >= prev_score:
|
||||
by_key[key] = row
|
||||
grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||||
for row in by_key.values():
|
||||
grouped[row["symbol"]].append(row)
|
||||
for periods in grouped.values():
|
||||
periods.sort(key=lambda item: item["period_end_date"])
|
||||
return grouped, {
|
||||
"deduped_rows": len(by_key),
|
||||
"duplicate_rows": duplicate_rows,
|
||||
"restated_rows": restated_rows,
|
||||
}
|
||||
|
||||
|
||||
def match_cost(event: dict[str, Any], period: dict[str, Any]) -> float:
|
||||
delta = (event["announce_date"] - period["period_end_date"]).days
|
||||
penalty = _MISSING_SESSION_PENALTY if event.get("session") == "unknown" else 0.0
|
||||
return float(abs(delta - _TYPICAL_ANNOUNCE_LAG_DAYS)) + penalty
|
||||
|
||||
|
||||
def align_symbol(
|
||||
events: list[dict[str, Any]],
|
||||
periods: list[dict[str, Any]],
|
||||
*,
|
||||
max_lag_days: int,
|
||||
max_lead_days: int,
|
||||
) -> tuple[list[tuple[int, int]], list[int], list[int]]:
|
||||
"""Minimum-cost monotonic calendar-to-period alignment for one symbol.
|
||||
|
||||
Both lists must be sorted ascending (by announce_date / period_end_date). A
|
||||
match is allowed only when ``-max_lead_days <= announce_date - period_end <=
|
||||
max_lag_days``. Returns (matches, unmatched_event_indices,
|
||||
unmatched_period_indices).
|
||||
"""
|
||||
n_events = len(events)
|
||||
n_periods = len(periods)
|
||||
scores = [[0.0] * (n_periods + 1) for _ in range(n_events + 1)]
|
||||
choices = [[""] * (n_periods + 1) for _ in range(n_events + 1)]
|
||||
for e in range(n_events - 1, -1, -1):
|
||||
scores[e][n_periods] = scores[e + 1][n_periods] + SKIP_EVENT_COST
|
||||
choices[e][n_periods] = "event"
|
||||
for p in range(n_periods - 1, -1, -1):
|
||||
scores[n_events][p] = scores[n_events][p + 1] + SKIP_PERIOD_COST
|
||||
choices[n_events][p] = "period"
|
||||
|
||||
for e in range(n_events - 1, -1, -1):
|
||||
for p in range(n_periods - 1, -1, -1):
|
||||
options = [
|
||||
(scores[e + 1][p] + SKIP_EVENT_COST, 2, "event"),
|
||||
(scores[e][p + 1] + SKIP_PERIOD_COST, 1, "period"),
|
||||
]
|
||||
delta = (events[e]["announce_date"] - periods[p]["period_end_date"]).days
|
||||
if -max_lead_days <= delta <= max_lag_days:
|
||||
options.append(
|
||||
(scores[e + 1][p + 1] + match_cost(events[e], periods[p]), 0, "match")
|
||||
)
|
||||
score, _, choice = min(options)
|
||||
scores[e][p] = score
|
||||
choices[e][p] = choice
|
||||
|
||||
matches: list[tuple[int, int]] = []
|
||||
unmatched_events: list[int] = []
|
||||
unmatched_periods: list[int] = []
|
||||
e = p = 0
|
||||
while e < n_events or p < n_periods:
|
||||
if e >= n_events:
|
||||
unmatched_periods.extend(range(p, n_periods))
|
||||
break
|
||||
if p >= n_periods:
|
||||
unmatched_events.extend(range(e, n_events))
|
||||
break
|
||||
choice = choices[e][p]
|
||||
if choice == "match":
|
||||
matches.append((e, p))
|
||||
e += 1
|
||||
p += 1
|
||||
elif choice == "period":
|
||||
unmatched_periods.append(p)
|
||||
p += 1
|
||||
else:
|
||||
unmatched_events.append(e)
|
||||
e += 1
|
||||
return matches, unmatched_events, unmatched_periods
|
||||
+942
-225
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,154 @@
|
||||
"""Refresh the fundamentals compat cache from local SEC/Dolt bulk data.
|
||||
|
||||
``fundamental_data`` is the table scoring reads. This is its only writer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import insert_for_session
|
||||
from app.models.fundamental import FundamentalData
|
||||
from app.models.score import CompositeScore, DimensionScore
|
||||
from app.services import fundamentals_candidate_service
|
||||
|
||||
_SCORE_FIELDS = ("pe_ratio", "revenue_growth", "earnings_surprise")
|
||||
|
||||
|
||||
async def refresh(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
today: date | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Replace every ticker's compat-cache row in one database transaction.
|
||||
|
||||
Candidate values are assembled before the first write and use only local
|
||||
PostgreSQL tables. A failure rolls the whole refresh back. Only changes to
|
||||
the three scoring inputs invalidate cached scores; market cap and the next
|
||||
earnings date are display-only.
|
||||
"""
|
||||
refreshed_at = now or datetime.now(timezone.utc)
|
||||
candidates = await fundamentals_candidate_service.build_candidates(
|
||||
db, today=today
|
||||
)
|
||||
ticker_ids = [candidate.ticker_id for candidate in candidates]
|
||||
existing = await _existing_by_ticker(db, ticker_ids)
|
||||
changed_ids = {
|
||||
candidate.ticker_id
|
||||
for candidate in candidates
|
||||
if _score_inputs_changed(existing.get(candidate.ticker_id), candidate)
|
||||
}
|
||||
|
||||
for candidate in candidates:
|
||||
unavailable_json = json.dumps(
|
||||
candidate.unavailable_fields, sort_keys=True
|
||||
)
|
||||
stmt = insert_for_session(db, FundamentalData).values(
|
||||
ticker_id=candidate.ticker_id,
|
||||
pe_ratio=candidate.pe_ratio,
|
||||
revenue_growth=candidate.revenue_growth,
|
||||
earnings_surprise=candidate.earnings_surprise,
|
||||
market_cap=candidate.market_cap,
|
||||
next_earnings_date=candidate.next_earnings_date,
|
||||
fetched_at=refreshed_at,
|
||||
unavailable_fields_json=unavailable_json,
|
||||
)
|
||||
await db.execute(
|
||||
stmt.on_conflict_do_update(
|
||||
index_elements=["ticker_id"],
|
||||
set_={
|
||||
"pe_ratio": stmt.excluded.pe_ratio,
|
||||
"revenue_growth": stmt.excluded.revenue_growth,
|
||||
"earnings_surprise": stmt.excluded.earnings_surprise,
|
||||
"market_cap": stmt.excluded.market_cap,
|
||||
"next_earnings_date": stmt.excluded.next_earnings_date,
|
||||
"fetched_at": stmt.excluded.fetched_at,
|
||||
"unavailable_fields_json": (
|
||||
stmt.excluded.unavailable_fields_json
|
||||
),
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
dimension_ids = await _fundamental_dimension_ids(db, changed_ids)
|
||||
composite_ids = await _composite_ids(db, changed_ids)
|
||||
if dimension_ids:
|
||||
await db.execute(
|
||||
update(DimensionScore)
|
||||
.where(DimensionScore.ticker_id.in_(dimension_ids))
|
||||
.values(is_stale=True)
|
||||
)
|
||||
if composite_ids:
|
||||
await db.execute(
|
||||
update(CompositeScore)
|
||||
.where(CompositeScore.ticker_id.in_(composite_ids))
|
||||
.values(is_stale=True)
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
return {
|
||||
"refreshed": len(candidates),
|
||||
"score_inputs_changed": len(changed_ids),
|
||||
"dimension_scores_staled": len(dimension_ids),
|
||||
"composite_scores_staled": len(composite_ids),
|
||||
}
|
||||
|
||||
|
||||
async def _existing_by_ticker(
|
||||
db: AsyncSession, ticker_ids: list[int]
|
||||
) -> dict[int, FundamentalData]:
|
||||
if not ticker_ids:
|
||||
return {}
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(FundamentalData).where(
|
||||
FundamentalData.ticker_id.in_(ticker_ids)
|
||||
)
|
||||
)
|
||||
).scalars()
|
||||
return {row.ticker_id: row for row in rows}
|
||||
|
||||
|
||||
async def _fundamental_dimension_ids(
|
||||
db: AsyncSession, ticker_ids: set[int]
|
||||
) -> set[int]:
|
||||
if not ticker_ids:
|
||||
return set()
|
||||
rows = await db.execute(
|
||||
select(DimensionScore.ticker_id).where(
|
||||
DimensionScore.ticker_id.in_(ticker_ids),
|
||||
DimensionScore.dimension == "fundamental",
|
||||
)
|
||||
)
|
||||
return set(rows.scalars())
|
||||
|
||||
|
||||
async def _composite_ids(
|
||||
db: AsyncSession, ticker_ids: set[int]
|
||||
) -> set[int]:
|
||||
if not ticker_ids:
|
||||
return set()
|
||||
rows = await db.execute(
|
||||
select(CompositeScore.ticker_id).where(
|
||||
CompositeScore.ticker_id.in_(ticker_ids)
|
||||
)
|
||||
)
|
||||
return set(rows.scalars())
|
||||
|
||||
|
||||
def _score_inputs_changed(
|
||||
existing: FundamentalData | None,
|
||||
candidate: fundamentals_candidate_service.CandidateFundamentals,
|
||||
) -> bool:
|
||||
if existing is None:
|
||||
return True
|
||||
return any(
|
||||
getattr(existing, field) != getattr(candidate, field)
|
||||
for field in _SCORE_FIELDS
|
||||
)
|
||||
@@ -1,22 +1,19 @@
|
||||
"""Fundamental data service.
|
||||
"""Fundamental data read access.
|
||||
|
||||
Stores fundamental data (P/E, revenue growth, earnings surprise, market cap)
|
||||
and marks the fundamental dimension score as stale on new data.
|
||||
``fundamental_data`` is the compat cache scoring reads. It is written solely by
|
||||
``fundamental_data_refresh_service`` from SEC snapshots, Dolt earnings events and
|
||||
stored closes; nothing fetches it per ticker.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import insert_for_session
|
||||
from app.exceptions import NotFoundError
|
||||
from app.models.fundamental import FundamentalData
|
||||
from app.models.score import DimensionScore
|
||||
from app.models.ticker import Ticker
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -32,88 +29,6 @@ async def _get_ticker(db: AsyncSession, symbol: str) -> Ticker:
|
||||
return ticker
|
||||
|
||||
|
||||
async def store_fundamental(
|
||||
db: AsyncSession,
|
||||
symbol: str,
|
||||
pe_ratio: float | None = None,
|
||||
revenue_growth: float | None = None,
|
||||
earnings_surprise: float | None = None,
|
||||
market_cap: float | None = None,
|
||||
next_earnings_date=None,
|
||||
unavailable_fields: dict[str, str] | None = None,
|
||||
) -> FundamentalData:
|
||||
"""Store or update fundamental data for a ticker.
|
||||
|
||||
Keeps a single latest snapshot per ticker. On new data, marks the
|
||||
fundamental dimension score as stale (if one exists).
|
||||
"""
|
||||
ticker = await _get_ticker(db, symbol)
|
||||
|
||||
# Check for existing record
|
||||
result = await db.execute(
|
||||
select(FundamentalData).where(FundamentalData.ticker_id == ticker.id)
|
||||
)
|
||||
existing = result.scalar_one_or_none()
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
unavailable_fields_json = json.dumps(unavailable_fields or {})
|
||||
|
||||
if existing is not None:
|
||||
existing.pe_ratio = pe_ratio
|
||||
existing.revenue_growth = revenue_growth
|
||||
existing.earnings_surprise = earnings_surprise
|
||||
existing.market_cap = market_cap
|
||||
existing.next_earnings_date = next_earnings_date
|
||||
existing.fetched_at = now
|
||||
existing.unavailable_fields_json = unavailable_fields_json
|
||||
record = existing
|
||||
else:
|
||||
stmt = insert_for_session(db, FundamentalData).values(
|
||||
ticker_id=ticker.id,
|
||||
pe_ratio=pe_ratio,
|
||||
revenue_growth=revenue_growth,
|
||||
earnings_surprise=earnings_surprise,
|
||||
market_cap=market_cap,
|
||||
next_earnings_date=next_earnings_date,
|
||||
fetched_at=now,
|
||||
unavailable_fields_json=unavailable_fields_json,
|
||||
)
|
||||
await db.execute(
|
||||
stmt.on_conflict_do_update(
|
||||
index_elements=["ticker_id"],
|
||||
set_={
|
||||
"pe_ratio": stmt.excluded.pe_ratio,
|
||||
"revenue_growth": stmt.excluded.revenue_growth,
|
||||
"earnings_surprise": stmt.excluded.earnings_surprise,
|
||||
"market_cap": stmt.excluded.market_cap,
|
||||
"next_earnings_date": stmt.excluded.next_earnings_date,
|
||||
"fetched_at": stmt.excluded.fetched_at,
|
||||
"unavailable_fields_json": stmt.excluded.unavailable_fields_json,
|
||||
},
|
||||
)
|
||||
)
|
||||
result = await db.execute(
|
||||
select(FundamentalData).where(FundamentalData.ticker_id == ticker.id)
|
||||
)
|
||||
record = result.scalar_one()
|
||||
|
||||
# Mark fundamental dimension score as stale if it exists
|
||||
# TODO: Use DimensionScore service when built
|
||||
dim_result = await db.execute(
|
||||
select(DimensionScore).where(
|
||||
DimensionScore.ticker_id == ticker.id,
|
||||
DimensionScore.dimension == "fundamental",
|
||||
)
|
||||
)
|
||||
dim_score = dim_result.scalar_one_or_none()
|
||||
if dim_score is not None:
|
||||
dim_score.is_stale = True
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(record)
|
||||
return record
|
||||
|
||||
|
||||
async def get_fundamental(
|
||||
db: AsyncSession,
|
||||
symbol: str,
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
"""Assemble the additive fundamentals API v1 objects (earnings, metrics,
|
||||
valuation, reads) from SEC snapshots + Dolt earnings + the latest price.
|
||||
|
||||
Strictly additive: the router merges these into the existing FundamentalResponse
|
||||
without touching legacy fields. Valuation ratios are computed at REQUEST TIME from
|
||||
the stored snapshots + the latest ohlcv close (no stored valuation). Peer stats are
|
||||
batched and CIK-deduplicated; invalid valuation inputs are guarded to null.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections import defaultdict
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.earnings_event import EarningsEvent
|
||||
from app.models.fundamental_snapshot import FundamentalSnapshot
|
||||
from app.models.ohlcv import OHLCVRecord
|
||||
from app.models.ticker import Ticker
|
||||
from app.services import fundamentals_derivation as deriv
|
||||
from app.services import fundamentals_peers as peers
|
||||
from app.services import fundamentals_reads as reads
|
||||
|
||||
# The fixed metric row set — every key always present, value null when unavailable.
|
||||
METRIC_KEYS = (
|
||||
"revenue_growth_yoy", "eps_growth_yoy", "operating_margin", "fcf_margin",
|
||||
"net_debt", "net_debt_to_ebitda", "share_count_change_yoy",
|
||||
)
|
||||
|
||||
|
||||
async def build_fundamentals_v1(db: AsyncSession, symbol: str, *, today: date | None = None) -> dict[str, Any]:
|
||||
today = today or _ny_today()
|
||||
ticker = await _ticker_by_symbol(db, symbol)
|
||||
|
||||
earnings = await _build_earnings(db, ticker.id, today) if ticker else _empty_earnings()
|
||||
if ticker is None or not ticker.cik:
|
||||
# No SEC identity: metrics present but null, valuation null, empty reads.
|
||||
return {"earnings": earnings, "metrics": _empty_metrics(), "valuation": None,
|
||||
"reads": _empty_reads()}
|
||||
|
||||
subject_cik = ticker.cik
|
||||
derived = deriv.derive((await _snapshots_for(db, [subject_cik])).get(subject_cik, []))
|
||||
|
||||
two = peers.two_digit_sic(ticker.sic)
|
||||
peer_derived: dict[str, deriv.DerivedFundamentals] = {}
|
||||
peer_price_by_cik: dict[str, tuple[float, date] | None] = {}
|
||||
if two:
|
||||
# Subject's representative is the REQUESTED ticker (so its price is used for
|
||||
# the subject in the peer set); other issuers pick a deterministic-by-symbol rep.
|
||||
group = await _peer_group(db, two, subject_cik, ticker.id)
|
||||
peer_snaps = await _snapshots_for(db, list(group))
|
||||
peer_derived = {cik: deriv.derive(rows) for cik, rows in peer_snaps.items()}
|
||||
closes = await _latest_closes(db, set(group.values()))
|
||||
peer_price_by_cik = {cik: closes.get(tid) for cik, tid in group.items()}
|
||||
|
||||
subject_price = await _latest_close(db, ticker.id)
|
||||
metrics = _build_metrics(derived, peer_derived, two)
|
||||
valuation = _build_valuation(derived, subject_price, peer_derived, peer_price_by_cik, two)
|
||||
reads_obj = _build_reads(metrics, valuation)
|
||||
return {"earnings": earnings, "metrics": metrics, "valuation": valuation, "reads": reads_obj}
|
||||
|
||||
|
||||
# -- earnings ----------------------------------------------------------------
|
||||
|
||||
async def _build_earnings(db, ticker_id: int, today: date) -> dict[str, Any]:
|
||||
rows = (await db.execute(
|
||||
select(EarningsEvent).where(EarningsEvent.ticker_id == ticker_id)
|
||||
)).scalars().all()
|
||||
# Same-day earnings are UPCOMING (days_until 0); recent is strictly earlier.
|
||||
upcoming = sorted((e for e in rows if e.announce_date >= today), key=lambda e: e.announce_date)
|
||||
past = sorted((e for e in rows if e.announce_date < today), key=lambda e: e.announce_date, reverse=True)
|
||||
|
||||
nxt = None
|
||||
if upcoming:
|
||||
e = upcoming[0]
|
||||
nxt = {"date": e.announce_date.isoformat(), "session": e.session,
|
||||
"days_until": (e.announce_date - today).days}
|
||||
recent = [{
|
||||
"announce_date": e.announce_date.isoformat(),
|
||||
"period_end": _iso(e.period_end),
|
||||
"eps_estimate": e.eps_estimate,
|
||||
"eps_actual": e.eps_actual,
|
||||
"surprise_pct": _surprise_pct(e.eps_estimate, e.eps_actual),
|
||||
} for e in past[:4]]
|
||||
return {"next": nxt, "recent": recent}
|
||||
|
||||
|
||||
def _surprise_pct(estimate, actual):
|
||||
if estimate is None or actual is None or estimate == 0:
|
||||
return None
|
||||
return round((actual - estimate) / abs(estimate) * 100.0, 2)
|
||||
|
||||
|
||||
# -- metrics -----------------------------------------------------------------
|
||||
|
||||
def _build_metrics(derived, peer_derived, two: str | None) -> list[dict[str, Any]]:
|
||||
out = []
|
||||
for key in METRIC_KEYS:
|
||||
series = derived.metrics.get(key)
|
||||
value = series.value if series else None
|
||||
history = [{"period_end": _iso(p.period_end), "value": p.value} for p in (series.history if series else [])]
|
||||
industry = None
|
||||
if two and peer_derived and key in peers.HIGHER_IS_BETTER:
|
||||
group_values = [
|
||||
(pd.metrics.get(key).value if pd.metrics.get(key) else None)
|
||||
for pd in peer_derived.values()
|
||||
]
|
||||
stat = peers.peer_stat_for(key, value, group_values)
|
||||
if stat:
|
||||
industry = {"label": f"SIC {two} peers", "median": round(stat.median, 4),
|
||||
"favorable_percentile": stat.favorable_percentile, "peer_count": stat.peer_count}
|
||||
out.append({
|
||||
"key": key,
|
||||
"value": value,
|
||||
"history": history,
|
||||
"industry": industry,
|
||||
"period_end": _iso(series.period_end) if series else None,
|
||||
"filed_date": _iso(series.filed_date) if series else None,
|
||||
"caveat": series.caveat if series else None,
|
||||
"source": "sec",
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
# -- valuation (request-time) ------------------------------------------------
|
||||
|
||||
def _build_valuation(derived, subject_price, peer_derived, peer_price_by_cik, two) -> dict[str, Any] | None:
|
||||
if derived.latest_period_end is None:
|
||||
return None # no snapshots yet
|
||||
price = subject_price[0] if subject_price else None
|
||||
price_date = subject_price[1] if subject_price else None
|
||||
if not _finite(price) or price <= 0:
|
||||
return None # no usable price -> valuation null (approved contract)
|
||||
|
||||
pe = _pe(price, derived.ttm_diluted_eps)
|
||||
market_cap = _market_cap(price, derived.shares_outstanding)
|
||||
fcf_yield = _fcf_yield(derived.ttm_fcf, market_cap)
|
||||
|
||||
pe_industry = fcf_yield_industry = None
|
||||
if two and peer_derived:
|
||||
pe_values = [_pe(_p(peer_price_by_cik.get(cik)), pd.ttm_diluted_eps) for cik, pd in peer_derived.items()]
|
||||
fy_values = [
|
||||
_fcf_yield(pd.ttm_fcf, _market_cap(_p(peer_price_by_cik.get(cik)), pd.shares_outstanding))
|
||||
for cik, pd in peer_derived.items()
|
||||
]
|
||||
pe_industry = _industry("pe", pe, pe_values, two)
|
||||
fcf_yield_industry = _industry("fcf_yield", fcf_yield, fy_values, two)
|
||||
|
||||
return {
|
||||
"pe": _round(pe, 2),
|
||||
"fcf_yield": _round(fcf_yield, 2),
|
||||
"market_cap_est": _round(market_cap, 0),
|
||||
# market_cap_est and fcf_yield both rest on the share count. When it came
|
||||
# from the weighted-average diluted fallback (multi-class issuers, whose
|
||||
# per-class cover-page count is absent from companyfacts), say so rather
|
||||
# than presenting a period average as a point-in-time count.
|
||||
"shares_estimated": bool(
|
||||
market_cap is not None and derived.shares_outstanding_estimated
|
||||
),
|
||||
# A null P/E is ambiguous: no earnings data, or earnings we deliberately
|
||||
# suppressed. Only the latter carries a caveat, so a split-contaminated
|
||||
# TTM says why instead of looking like missing data.
|
||||
"pe_caveat": derived.ttm_diluted_eps_caveat if pe is None else None,
|
||||
"pe_industry": pe_industry,
|
||||
"fcf_yield_industry": fcf_yield_industry,
|
||||
"price_date": _iso(price_date),
|
||||
}
|
||||
|
||||
|
||||
def _pe(price, ttm_eps):
|
||||
if not _finite(price) or price <= 0 or not _finite(ttm_eps) or ttm_eps <= 0:
|
||||
return None
|
||||
return price / ttm_eps
|
||||
|
||||
|
||||
def _market_cap(price, shares):
|
||||
if not _finite(price) or price <= 0 or not _finite(shares) or shares <= 0:
|
||||
return None
|
||||
return price * shares
|
||||
|
||||
|
||||
def _fcf_yield(ttm_fcf, market_cap):
|
||||
if not _finite(ttm_fcf) or not _finite(market_cap) or market_cap <= 0:
|
||||
return None
|
||||
return ttm_fcf / market_cap * 100.0
|
||||
|
||||
|
||||
def _industry(key, subject, group_values, two):
|
||||
stat = peers.peer_stat_for(key, subject, group_values)
|
||||
if stat is None:
|
||||
return None
|
||||
return {"label": f"SIC {two} peers", "median": round(stat.median, 4),
|
||||
"favorable_percentile": stat.favorable_percentile, "peer_count": stat.peer_count}
|
||||
|
||||
|
||||
# -- reads -------------------------------------------------------------------
|
||||
|
||||
_READ_KEYS = METRIC_KEYS + ("pe", "fcf_yield")
|
||||
|
||||
|
||||
def _build_reads(metrics: list[dict], valuation: dict | None) -> dict[str, Any]:
|
||||
by_metric = {m["key"]: m for m in metrics}
|
||||
|
||||
def hist(key):
|
||||
return [_Pt(p["value"]) for p in by_metric.get(key, {}).get("history", [])]
|
||||
|
||||
growth = reads.growth_read(hist("revenue_growth_yoy"))
|
||||
eps_growth = reads.growth_read(hist("eps_growth_yoy"))
|
||||
op_margin = reads.margin_read(hist("operating_margin"))
|
||||
fcf_margin = reads.margin_read(hist("fcf_margin"))
|
||||
share = reads.share_count_read(by_metric.get("share_count_change_yoy", {}).get("value"))
|
||||
leverage = reads.peer_read("net_debt_to_ebitda", _pct(by_metric.get("net_debt_to_ebitda", {}).get("industry")))
|
||||
pe_read = reads.peer_read("pe", _pct(valuation.get("pe_industry"))) if valuation else None
|
||||
fcf_yield_read = reads.peer_read("fcf_yield", _pct(valuation.get("fcf_yield_industry"))) if valuation else None
|
||||
|
||||
# Fixed by_key map over every metric + pe + fcf_yield (null where unavailable).
|
||||
by_key: dict[str, str | None] = {k: None for k in _READ_KEYS}
|
||||
by_key.update({
|
||||
"revenue_growth_yoy": growth,
|
||||
"eps_growth_yoy": eps_growth,
|
||||
"operating_margin": op_margin,
|
||||
"fcf_margin": fcf_margin,
|
||||
"share_count_change_yoy": share,
|
||||
"net_debt_to_ebitda": leverage,
|
||||
"pe": pe_read,
|
||||
"fcf_yield": fcf_yield_read,
|
||||
})
|
||||
header = reads.header_sentence(growth, op_margin, pe_read or fcf_yield_read) or None
|
||||
return {"header": header, "by_key": by_key}
|
||||
|
||||
|
||||
def _empty_reads() -> dict[str, Any]:
|
||||
return {"header": None, "by_key": {k: None for k in _READ_KEYS}}
|
||||
|
||||
|
||||
class _Pt:
|
||||
__slots__ = ("value",)
|
||||
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
|
||||
def _pct(industry: dict | None):
|
||||
return industry.get("favorable_percentile") if industry else None
|
||||
|
||||
|
||||
# -- queries -----------------------------------------------------------------
|
||||
|
||||
async def _ticker_by_symbol(db, symbol: str) -> Ticker | None:
|
||||
return (await db.execute(
|
||||
select(Ticker).where(Ticker.symbol == symbol.strip().upper())
|
||||
)).scalar_one_or_none()
|
||||
|
||||
|
||||
async def _snapshots_for(db, ciks) -> dict[str, list]:
|
||||
out: dict[str, list] = defaultdict(list)
|
||||
if not ciks:
|
||||
return out
|
||||
rows = (await db.execute(
|
||||
select(FundamentalSnapshot).where(FundamentalSnapshot.cik.in_(list(ciks)))
|
||||
)).scalars().all()
|
||||
for r in rows:
|
||||
out[r.cik].append(r)
|
||||
return out
|
||||
|
||||
|
||||
async def _peer_group(db, two: str, subject_cik: str, subject_tid: int) -> dict[str, int]:
|
||||
"""{cik: representative ticker_id} for tracked issuers in the 2-digit SIC group,
|
||||
CIK-deduplicated. Each issuer's representative is its lexicographically-smallest
|
||||
symbol (deterministic), EXCEPT the subject issuer, which uses the requested
|
||||
ticker — so a multi-class subject (GOOGL) is priced by the requested class, not
|
||||
an arbitrary sibling (GOOG)."""
|
||||
rows = (await db.execute(
|
||||
select(Ticker.cik, Ticker.id, Ticker.symbol)
|
||||
.where(Ticker.cik.is_not(None), func.substr(Ticker.sic, 1, 2) == two)
|
||||
)).all()
|
||||
rep: dict[str, tuple[int, str]] = {}
|
||||
for cik, tid, sym in rows:
|
||||
key = sym or ""
|
||||
if cik not in rep or key < rep[cik][1]:
|
||||
rep[cik] = (tid, key)
|
||||
group = {cik: tid for cik, (tid, _) in rep.items()}
|
||||
if subject_cik in group:
|
||||
group[subject_cik] = subject_tid # requested ticker prices the subject
|
||||
return group
|
||||
|
||||
|
||||
async def _latest_closes(db, ticker_ids: set[int]) -> dict[int, tuple[float, date]]:
|
||||
if not ticker_ids:
|
||||
return {}
|
||||
latest = (
|
||||
select(OHLCVRecord.ticker_id, func.max(OHLCVRecord.date).label("d"))
|
||||
.where(OHLCVRecord.ticker_id.in_(list(ticker_ids)))
|
||||
.group_by(OHLCVRecord.ticker_id)
|
||||
.subquery()
|
||||
)
|
||||
rows = (await db.execute(
|
||||
select(OHLCVRecord.ticker_id, OHLCVRecord.close, OHLCVRecord.date).join(
|
||||
latest, (OHLCVRecord.ticker_id == latest.c.ticker_id) & (OHLCVRecord.date == latest.c.d)
|
||||
)
|
||||
)).all()
|
||||
return {tid: (close, d) for tid, close, d in rows}
|
||||
|
||||
|
||||
async def _latest_close(db, ticker_id: int) -> tuple[float, date] | None:
|
||||
return (await _latest_closes(db, {ticker_id})).get(ticker_id)
|
||||
|
||||
|
||||
# -- helpers -----------------------------------------------------------------
|
||||
|
||||
def _empty_metrics() -> list[dict[str, Any]]:
|
||||
return [{"key": k, "value": None, "history": [], "industry": None,
|
||||
"period_end": None, "filed_date": None, "caveat": None,
|
||||
"source": "sec"} for k in METRIC_KEYS]
|
||||
|
||||
|
||||
def _empty_earnings() -> dict[str, Any]:
|
||||
return {"next": None, "recent": []}
|
||||
|
||||
|
||||
def _p(price_tuple):
|
||||
return price_tuple[0] if price_tuple else None
|
||||
|
||||
|
||||
def _finite(v) -> bool:
|
||||
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
|
||||
|
||||
|
||||
def _round(v, ndigits):
|
||||
return round(v, ndigits) if _finite(v) else None
|
||||
|
||||
|
||||
def _iso(d) -> str | None:
|
||||
return d.isoformat() if d else None
|
||||
|
||||
|
||||
def _ny_today() -> date:
|
||||
"""Today's New York calendar date — the market's day, not the server's."""
|
||||
return datetime.now(ZoneInfo("America/New_York")).date()
|
||||
@@ -0,0 +1,292 @@
|
||||
"""Local SEC/Dolt candidate values for the fundamentals compat cache.
|
||||
|
||||
This is the read path behind the ``fundamental_data`` refresh. It never contacts
|
||||
SEC or Dolt: every input comes from PostgreSQL, so price- and earnings-driven
|
||||
values can still refresh when an upstream import is unchanged or unavailable.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.earnings_event import EarningsEvent
|
||||
from app.models.fundamental_snapshot import FundamentalSnapshot
|
||||
from app.models.ohlcv import OHLCVRecord
|
||||
from app.models.ticker import Ticker
|
||||
from app.services import fundamentals_derivation as deriv
|
||||
from app.services import ticker_service
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CandidateFundamentals:
|
||||
ticker_id: int
|
||||
symbol: str
|
||||
cik: str | None
|
||||
pe_ratio: float | None
|
||||
revenue_growth: float | None
|
||||
earnings_surprise: float | None
|
||||
market_cap: float | None
|
||||
next_earnings_date: date | None
|
||||
price_date: date | None
|
||||
unavailable_fields: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
async def build_candidates(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
today: date | None = None,
|
||||
) -> list[CandidateFundamentals]:
|
||||
"""Derive current cache candidates using only already-stored data."""
|
||||
today = today or datetime.now(ZoneInfo("America/New_York")).date()
|
||||
tickers = list(
|
||||
(
|
||||
await db.execute(
|
||||
ticker_service.active_only(select(Ticker).order_by(Ticker.symbol))
|
||||
)
|
||||
).scalars()
|
||||
)
|
||||
if not tickers:
|
||||
return []
|
||||
|
||||
ticker_ids = [ticker.id for ticker in tickers]
|
||||
ciks = sorted({ticker.cik for ticker in tickers if ticker.cik})
|
||||
derived_by_cik = await _derived_by_cik(db, ciks)
|
||||
closes_by_ticker = await _latest_closes(db, ticker_ids)
|
||||
surprise_by_ticker, next_by_ticker = await _earnings_values(
|
||||
db, ticker_ids, today
|
||||
)
|
||||
|
||||
out: list[CandidateFundamentals] = []
|
||||
for ticker in tickers:
|
||||
derived = derived_by_cik.get(ticker.cik) if ticker.cik else None
|
||||
close = closes_by_ticker.get(ticker.id)
|
||||
price = close[0] if close is not None else None
|
||||
price_date = close[1] if close is not None else None
|
||||
growth_series = (
|
||||
derived.metrics.get("revenue_growth_yoy")
|
||||
if derived is not None
|
||||
else None
|
||||
)
|
||||
|
||||
pe_ratio = (
|
||||
_pe(price, derived.ttm_diluted_eps)
|
||||
if derived is not None
|
||||
else None
|
||||
)
|
||||
revenue_growth = (
|
||||
float(growth_series.value)
|
||||
if growth_series is not None and _finite(growth_series.value)
|
||||
else None
|
||||
)
|
||||
earnings_surprise = surprise_by_ticker.get(ticker.id)
|
||||
market_cap = (
|
||||
_market_cap(price, derived.shares_outstanding)
|
||||
if derived is not None
|
||||
else None
|
||||
)
|
||||
next_earnings_date = next_by_ticker.get(ticker.id)
|
||||
|
||||
out.append(
|
||||
CandidateFundamentals(
|
||||
ticker_id=ticker.id,
|
||||
symbol=ticker.symbol,
|
||||
cik=ticker.cik,
|
||||
pe_ratio=pe_ratio,
|
||||
revenue_growth=revenue_growth,
|
||||
earnings_surprise=earnings_surprise,
|
||||
market_cap=market_cap,
|
||||
next_earnings_date=next_earnings_date,
|
||||
price_date=price_date,
|
||||
unavailable_fields=_availability_metadata(
|
||||
derived=derived,
|
||||
price=price,
|
||||
pe_ratio=pe_ratio,
|
||||
revenue_growth=revenue_growth,
|
||||
earnings_surprise=earnings_surprise,
|
||||
market_cap=market_cap,
|
||||
next_earnings_date=next_earnings_date,
|
||||
),
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
async def _derived_by_cik(
|
||||
db: AsyncSession, ciks: list[str]
|
||||
) -> dict[str, deriv.DerivedFundamentals]:
|
||||
if not ciks:
|
||||
return {}
|
||||
grouped: dict[str, list[FundamentalSnapshot]] = defaultdict(list)
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(FundamentalSnapshot).where(FundamentalSnapshot.cik.in_(ciks))
|
||||
)
|
||||
).scalars()
|
||||
for row in rows:
|
||||
grouped[row.cik].append(row)
|
||||
return {cik: deriv.derive(grouped.get(cik, [])) for cik in ciks}
|
||||
|
||||
|
||||
async def _latest_closes(
|
||||
db: AsyncSession, ticker_ids: list[int]
|
||||
) -> dict[int, tuple[float, date]]:
|
||||
latest = (
|
||||
select(
|
||||
OHLCVRecord.ticker_id,
|
||||
func.max(OHLCVRecord.date).label("max_date"),
|
||||
)
|
||||
.where(OHLCVRecord.ticker_id.in_(ticker_ids))
|
||||
.group_by(OHLCVRecord.ticker_id)
|
||||
.subquery()
|
||||
)
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(
|
||||
OHLCVRecord.ticker_id,
|
||||
OHLCVRecord.close,
|
||||
OHLCVRecord.date,
|
||||
).join(
|
||||
latest,
|
||||
(OHLCVRecord.ticker_id == latest.c.ticker_id)
|
||||
& (OHLCVRecord.date == latest.c.max_date),
|
||||
)
|
||||
)
|
||||
).all()
|
||||
return {
|
||||
ticker_id: (float(close), close_date)
|
||||
for ticker_id, close, close_date in rows
|
||||
if _finite(close)
|
||||
}
|
||||
|
||||
|
||||
async def _earnings_values(
|
||||
db: AsyncSession,
|
||||
ticker_ids: list[int],
|
||||
today: date,
|
||||
) -> tuple[dict[int, float], dict[int, date]]:
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(EarningsEvent)
|
||||
.where(EarningsEvent.ticker_id.in_(ticker_ids))
|
||||
.order_by(EarningsEvent.ticker_id, EarningsEvent.announce_date.desc())
|
||||
)
|
||||
).scalars()
|
||||
surprises: dict[int, float] = {}
|
||||
upcoming: dict[int, date] = {}
|
||||
for row in rows:
|
||||
if row.announce_date >= today:
|
||||
current = upcoming.get(row.ticker_id)
|
||||
if current is None or row.announce_date < current:
|
||||
upcoming[row.ticker_id] = row.announce_date
|
||||
continue
|
||||
if row.ticker_id in surprises:
|
||||
continue
|
||||
surprise = _surprise(row.eps_estimate, row.eps_actual)
|
||||
if surprise is not None:
|
||||
surprises[row.ticker_id] = surprise
|
||||
return surprises, upcoming
|
||||
|
||||
|
||||
def _availability_metadata(
|
||||
*,
|
||||
derived: deriv.DerivedFundamentals | None,
|
||||
price: float | None,
|
||||
pe_ratio: float | None,
|
||||
revenue_growth: float | None,
|
||||
earnings_surprise: float | None,
|
||||
market_cap: float | None,
|
||||
next_earnings_date: date | None,
|
||||
) -> dict[str, str]:
|
||||
metadata: dict[str, str] = {}
|
||||
|
||||
if pe_ratio is not None:
|
||||
metadata["source_pe_ratio"] = "sec_facts+ohlcv_records"
|
||||
elif derived is None or derived.latest_period_end is None:
|
||||
metadata["pe_ratio"] = "no SEC fundamental snapshots"
|
||||
elif not _finite(price) or price <= 0:
|
||||
metadata["pe_ratio"] = "no usable PostgreSQL close"
|
||||
elif derived.ttm_diluted_eps_caveat:
|
||||
metadata["pe_ratio"] = derived.ttm_diluted_eps_caveat
|
||||
else:
|
||||
metadata["pe_ratio"] = "no positive SEC-derived TTM diluted EPS"
|
||||
|
||||
if revenue_growth is not None:
|
||||
metadata["source_revenue_growth"] = "sec_facts"
|
||||
else:
|
||||
metadata["revenue_growth"] = "SEC-derived TTM revenue growth unavailable"
|
||||
|
||||
if earnings_surprise is not None:
|
||||
metadata["source_earnings_surprise"] = "dolt_earnings"
|
||||
else:
|
||||
metadata["earnings_surprise"] = (
|
||||
"no completed earnings event with actual and nonzero estimate"
|
||||
)
|
||||
|
||||
if market_cap is not None:
|
||||
metadata["source_market_cap"] = "sec_facts+ohlcv_records"
|
||||
if derived is not None and derived.shares_outstanding_estimated:
|
||||
metadata["market_cap_estimated"] = (
|
||||
"shares use the SEC weighted-average diluted fallback"
|
||||
)
|
||||
elif derived is None or derived.latest_period_end is None:
|
||||
metadata["market_cap"] = "no SEC fundamental snapshots"
|
||||
elif not _finite(price) or price <= 0:
|
||||
metadata["market_cap"] = "no usable PostgreSQL close"
|
||||
else:
|
||||
metadata["market_cap"] = "SEC-derived shares outstanding unavailable"
|
||||
|
||||
if next_earnings_date is not None:
|
||||
metadata["source_next_earnings_date"] = "dolt_earnings"
|
||||
else:
|
||||
metadata["next_earnings_date"] = "no upcoming earnings event"
|
||||
return metadata
|
||||
|
||||
|
||||
def _surprise(
|
||||
estimate: float | None,
|
||||
actual: float | None,
|
||||
) -> float | None:
|
||||
if not _finite(estimate) or not _finite(actual) or estimate == 0:
|
||||
return None
|
||||
return (float(actual) - float(estimate)) / abs(float(estimate)) * 100.0
|
||||
|
||||
|
||||
def _pe(price: float | None, ttm_eps: float | None) -> float | None:
|
||||
if (
|
||||
not _finite(price)
|
||||
or price <= 0
|
||||
or not _finite(ttm_eps)
|
||||
or ttm_eps <= 0
|
||||
):
|
||||
return None
|
||||
return float(price) / float(ttm_eps)
|
||||
|
||||
|
||||
def _market_cap(
|
||||
price: float | None,
|
||||
shares_outstanding: float | None,
|
||||
) -> float | None:
|
||||
if (
|
||||
not _finite(price)
|
||||
or price <= 0
|
||||
or not _finite(shares_outstanding)
|
||||
or shares_outstanding <= 0
|
||||
):
|
||||
return None
|
||||
return float(price) * float(shares_outstanding)
|
||||
|
||||
|
||||
def _finite(value: Any) -> bool:
|
||||
return (
|
||||
isinstance(value, (int, float))
|
||||
and not isinstance(value, bool)
|
||||
and math.isfinite(value)
|
||||
)
|
||||
@@ -0,0 +1,396 @@
|
||||
"""Pure read-time derivation of fundamental metrics from stored snapshots.
|
||||
|
||||
`fundamental_snapshots` stores one immutable row per accession with **cumulative
|
||||
YTD** duration facts and period-end balance-sheet instants (A3). This module
|
||||
derives everything the UI/API shows — discrete quarters, Q4, TTM, YoY growth,
|
||||
margins, leverage, dilution, and the quarter tape — at read time, per the plan's
|
||||
schema decision. No I/O, no DB: it takes an issuer's snapshot rows (ORM rows or
|
||||
any objects with the same attributes) and returns structured metrics.
|
||||
|
||||
Rules:
|
||||
- **Amendment selection:** for each (fiscal_year, fiscal_period), the newest
|
||||
`accepted_at` wins **per field**, falling back to the newest row that actually
|
||||
reports one. A partial amendment (a 10-K/A adding Part III carries no financial
|
||||
facts) must not blank the period.
|
||||
- **Discrete quarter** = YTD(Qn) − YTD(Qn−1); Q1 = YTD(Q1); **Q4 = YTD(FY) −
|
||||
YTD(Q3)**. Any missing period → the derived value is null, never partial.
|
||||
- **TTM** = sum of the trailing four discrete quarters ending at a period.
|
||||
- Units follow app convention: percentages are percentage points (21.0 = 21%),
|
||||
net-debt/EBITDA is a multiple, net debt is dollars.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Iterable
|
||||
|
||||
_FP_TO_Q = {"Q1": 1, "Q2": 2, "Q3": 3, "FY": 4}
|
||||
_Q_TO_FP = {1: "Q1", 2: "Q2", 3: "Q3", 4: "FY"}
|
||||
_PREV_FP = {"Q2": "Q1", "Q3": "Q2", "FY": "Q3"}
|
||||
TAPE_LEN = 4 # quarter-tape length
|
||||
SPLIT_SUSPECT_SHARE_CHANGE_PCT = 25.0
|
||||
SPLIT_SENSITIVE_CAVEAT = (
|
||||
"Not comparable: share count changed at least 25%; possible split or "
|
||||
"corporate action."
|
||||
)
|
||||
|
||||
# Duration (flow) fields differenced from YTD into discrete quarters + summed to TTM.
|
||||
_FLOW_FIELDS = (
|
||||
"revenue", "net_income", "operating_income", "diluted_eps", "cfo", "capex",
|
||||
"depreciation_amortization",
|
||||
)
|
||||
# Reported facts resolved independently across a period's accessions (see
|
||||
# _merge_amendments); period identity/provenance is taken from the newest one.
|
||||
_MERGED_FIELDS = (
|
||||
*_FLOW_FIELDS,
|
||||
"cash_and_st_investments", "total_debt", "shares_outstanding",
|
||||
"shares_outstanding_date", "weighted_avg_diluted_shares",
|
||||
# period_start is set alongside revenue by the parser, so it follows the same
|
||||
# fallback: a bare amendment reports neither and must not blank it.
|
||||
"period_start",
|
||||
)
|
||||
_CARRIED_FIELDS = (
|
||||
"fiscal_year", "fiscal_period", "period_end", "filed_date",
|
||||
"accepted_at", "form", "accession", "cik",
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MetricPoint:
|
||||
period_end: date
|
||||
value: float | None
|
||||
|
||||
|
||||
@dataclass
|
||||
class MetricSeries:
|
||||
value: float | None = None
|
||||
history: list[MetricPoint] = field(default_factory=list) # oldest -> newest, <= TAPE_LEN
|
||||
period_end: date | None = None
|
||||
filed_date: date | None = None
|
||||
caveat: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class DerivedFundamentals:
|
||||
metrics: dict[str, MetricSeries] = field(default_factory=dict)
|
||||
# request-time valuation inputs (ratios are computed in the API with price)
|
||||
ttm_diluted_eps: float | None = None
|
||||
# Set when ttm_diluted_eps was suppressed rather than simply unavailable.
|
||||
ttm_diluted_eps_caveat: str | None = None
|
||||
ttm_fcf: float | None = None
|
||||
shares_outstanding: float | None = None
|
||||
# True when shares_outstanding came from the weighted-average diluted count
|
||||
# because the point-in-time cover-page count was absent (always so for
|
||||
# multi-class issuers). Consumers must label anything derived from it as
|
||||
# estimated — it is a period average, not a point-in-time count.
|
||||
shares_outstanding_estimated: bool = False
|
||||
latest_period_end: date | None = None
|
||||
latest_filed_date: date | None = None
|
||||
|
||||
|
||||
def _prev_q(fy: int, q: int) -> tuple[int, int]:
|
||||
return (fy, q - 1) if q > 1 else (fy - 1, 4)
|
||||
|
||||
|
||||
def derive(snapshots: Iterable[Any]) -> DerivedFundamentals:
|
||||
selected = _select_latest_per_period(snapshots)
|
||||
result = DerivedFundamentals()
|
||||
if not selected:
|
||||
return result
|
||||
|
||||
# Discrete quarter values per flow field: {field: {(fy, q): value}}.
|
||||
discrete = {f: _discrete_quarters(selected, f) for f in _FLOW_FIELDS}
|
||||
quarters = _ordered_quarters(selected) # chronological (fy, q) with a row
|
||||
latest = quarters[-1]
|
||||
latest_row = selected[(latest[0], _Q_TO_FP[latest[1]])]
|
||||
|
||||
result.latest_period_end = latest_row.period_end
|
||||
result.latest_filed_date = latest_row.filed_date
|
||||
result.shares_outstanding = getattr(latest_row, "shares_outstanding", None)
|
||||
if result.shares_outstanding is None:
|
||||
# Multi-class issuers (META, CMCSA, BRK-B, CHTR, FOXA, NWSA, LEN) report
|
||||
# the cover-page count per class, which is dimensional and so absent from
|
||||
# companyfacts — leaving market cap and FCF yield silently unavailable for
|
||||
# some of the largest names. The weighted-average diluted count is always
|
||||
# present and within ~0.6% of the true count where both exist, so fall
|
||||
# back to it and mark the result estimated rather than show nothing.
|
||||
result.shares_outstanding = getattr(latest_row, "weighted_avg_diluted_shares", None)
|
||||
result.shares_outstanding_estimated = result.shares_outstanding is not None
|
||||
result.ttm_diluted_eps = _ttm(discrete["diluted_eps"], *latest)
|
||||
ttm_cfo = _ttm(discrete["cfo"], *latest)
|
||||
ttm_capex = _ttm(discrete["capex"], *latest)
|
||||
result.ttm_fcf = None if ttm_cfo is None or ttm_capex is None else ttm_cfo - ttm_capex
|
||||
|
||||
# tape = the CONSECUTIVE run of up to TAPE_LEN quarters ending at the latest,
|
||||
# stopping at a gap — so trend text never compares non-adjacent periods.
|
||||
tape = _consecutive_suffix(quarters, TAPE_LEN)
|
||||
result.metrics = {
|
||||
"revenue_growth_yoy": _yoy_growth_series(discrete["revenue"], selected, tape),
|
||||
"eps_growth_yoy": _yoy_growth_series(discrete["diluted_eps"], selected, tape),
|
||||
"operating_margin": _margin_series(discrete["operating_income"], discrete["revenue"], selected, tape),
|
||||
"fcf_margin": _fcf_margin_series(discrete, selected, tape),
|
||||
"net_debt": _instant_series(selected, tape, _net_debt),
|
||||
"net_debt_to_ebitda": _leverage_series(selected, discrete, tape),
|
||||
"share_count_change_yoy": _share_change_series(selected, tape),
|
||||
}
|
||||
# TTM EPS sums four quarters of *per-share* values, so a split inside that
|
||||
# window mixes pre- and post-split units — the same distortion the guard
|
||||
# already catches for the series, and the one that produced BKNG's P/E of
|
||||
# 1.10. Left unguarded it does not merely mislead: a nonsense-low P/E clamps
|
||||
# to a perfect 100 fundamental sub-score, so it must null out like the rest.
|
||||
if _guard_split_sensitive_metrics(result.metrics):
|
||||
result.ttm_diluted_eps = None
|
||||
result.ttm_diluted_eps_caveat = SPLIT_SENSITIVE_CAVEAT
|
||||
for series in result.metrics.values():
|
||||
series.period_end = latest_row.period_end
|
||||
series.filed_date = latest_row.filed_date
|
||||
return result
|
||||
|
||||
|
||||
# -- period selection --------------------------------------------------------
|
||||
|
||||
def _select_latest_per_period(snapshots: Iterable[Any]) -> dict[tuple[int, str], Any]:
|
||||
grouped: dict[tuple[int, str], list[Any]] = {}
|
||||
for row in snapshots:
|
||||
fp = getattr(row, "fiscal_period", None)
|
||||
fy = getattr(row, "fiscal_year", None)
|
||||
if fp not in _FP_TO_Q or fy is None:
|
||||
continue
|
||||
grouped.setdefault((fy, fp), []).append(row)
|
||||
return {key: _merge_amendments(rows) for key, rows in grouped.items()}
|
||||
|
||||
|
||||
def _merge_amendments(rows: list[Any]) -> Any:
|
||||
"""Resolve one period from its accessions: newest wins, per field.
|
||||
|
||||
Amendments are frequently partial — a 10-K/A filed only to add Part III
|
||||
reports no financial facts at all. Taking the newest accession wholesale
|
||||
would blank every field it omits and null the period downstream (and with
|
||||
it TTM and YoY, which need an unbroken quarter chain), so each field falls
|
||||
back to the newest accession that actually reports it.
|
||||
|
||||
Only rows sharing the newest row's ``period_end`` are merged. A same-key row
|
||||
covering a *different* period is a mislabelled filing, not an amendment, and
|
||||
blending the two would silently mix fiscal years.
|
||||
"""
|
||||
if len(rows) == 1:
|
||||
return rows[0]
|
||||
ordered = sorted(rows, key=_amendment_order, reverse=True) # newest first
|
||||
newest = ordered[0]
|
||||
same_period = [
|
||||
row
|
||||
for row in ordered
|
||||
if getattr(row, "period_end", None) == getattr(newest, "period_end", None)
|
||||
]
|
||||
if len(same_period) == 1:
|
||||
return newest
|
||||
merged = SimpleNamespace(**{name: getattr(newest, name, None) for name in _CARRIED_FIELDS})
|
||||
for name in _MERGED_FIELDS:
|
||||
merged_value = None
|
||||
for row in same_period: # newest first
|
||||
value = getattr(row, name, None)
|
||||
if value is not None:
|
||||
merged_value = value
|
||||
break
|
||||
setattr(merged, name, merged_value)
|
||||
return merged
|
||||
|
||||
|
||||
def _amendment_order(row: Any) -> tuple[bool, Any]:
|
||||
# (has-timestamp, timestamp) so a row without one sorts oldest instead of
|
||||
# raising when compared against a row that has one.
|
||||
accepted = _accepted(row)
|
||||
return (accepted is not None, accepted)
|
||||
|
||||
|
||||
def _accepted(row: Any):
|
||||
return getattr(row, "accepted_at", None) or getattr(row, "filed_date", None)
|
||||
|
||||
|
||||
def _ordered_quarters(selected: dict[tuple[int, str], Any]) -> list[tuple[int, int]]:
|
||||
return sorted((fy, _FP_TO_Q[fp]) for (fy, fp) in selected)
|
||||
|
||||
|
||||
def _consecutive_suffix(quarters: list[tuple[int, int]], n: int) -> list[tuple[int, int]]:
|
||||
"""The run of up to n quarters ending at the latest, walking back only through
|
||||
adjacent periods (stop at the first gap). Returned oldest -> newest."""
|
||||
if not quarters:
|
||||
return []
|
||||
present = set(quarters)
|
||||
run = [quarters[-1]]
|
||||
cur = quarters[-1]
|
||||
while len(run) < n:
|
||||
prev = _prev_q(*cur)
|
||||
if prev not in present:
|
||||
break
|
||||
run.append(prev)
|
||||
cur = prev
|
||||
run.reverse()
|
||||
return run
|
||||
|
||||
|
||||
# -- discrete + TTM ----------------------------------------------------------
|
||||
|
||||
def _discrete_quarters(selected: dict[tuple[int, str], Any], field_name: str) -> dict[tuple[int, int], float]:
|
||||
out: dict[tuple[int, int], float] = {}
|
||||
for (fy, fp), row in selected.items():
|
||||
val = _discrete_value(selected, fy, fp, field_name)
|
||||
if val is not None:
|
||||
out[(fy, _FP_TO_Q[fp])] = val
|
||||
return out
|
||||
|
||||
|
||||
def _discrete_value(selected, fy: int, fp: str, field_name: str) -> float | None:
|
||||
cur = getattr(selected[(fy, fp)], field_name, None)
|
||||
if cur is None:
|
||||
return None
|
||||
if fp == "Q1":
|
||||
return cur
|
||||
prev = selected.get((fy, _PREV_FP[fp]))
|
||||
prev_val = getattr(prev, field_name, None) if prev is not None else None
|
||||
if prev_val is None:
|
||||
return None
|
||||
return cur - prev_val
|
||||
|
||||
|
||||
def _ttm(dq: dict[tuple[int, int], float], fy: int, q: int) -> float | None:
|
||||
keys = [(fy, q)]
|
||||
k = (fy, q)
|
||||
for _ in range(3):
|
||||
k = _prev_q(*k)
|
||||
keys.append(k)
|
||||
vals = [dq.get(kk) for kk in keys]
|
||||
if any(v is None for v in vals):
|
||||
return None
|
||||
return sum(vals)
|
||||
|
||||
|
||||
def _pct_change(cur: float | None, prior: float | None) -> float | None:
|
||||
# A non-positive prior makes a YoY % meaningless (e.g. loss->profit), so null it.
|
||||
if cur is None or prior is None or prior <= 0:
|
||||
return None
|
||||
return (cur / prior - 1.0) * 100.0
|
||||
|
||||
|
||||
# -- per-metric series (value at latest + tape history) ----------------------
|
||||
|
||||
def _period_end(selected, fy: int, q: int) -> date | None:
|
||||
row = selected.get((fy, _Q_TO_FP[q]))
|
||||
return row.period_end if row is not None else None
|
||||
|
||||
|
||||
def _yoy_growth_series(dq, selected, tape) -> MetricSeries:
|
||||
pts = []
|
||||
for (fy, q) in tape:
|
||||
cur, prior = _ttm(dq, fy, q), _ttm(dq, fy - 1, q)
|
||||
pts.append(MetricPoint(_period_end(selected, fy, q), _pct_change(cur, prior)))
|
||||
return _series(pts)
|
||||
|
||||
|
||||
def _margin_series(num_dq, den_dq, selected, tape) -> MetricSeries:
|
||||
pts = []
|
||||
for (fy, q) in tape:
|
||||
num, den = _ttm(num_dq, fy, q), _ttm(den_dq, fy, q)
|
||||
val = None if num is None or not den else num / den * 100.0
|
||||
pts.append(MetricPoint(_period_end(selected, fy, q), val))
|
||||
return _series(pts)
|
||||
|
||||
|
||||
def _fcf_margin_series(discrete, selected, tape) -> MetricSeries:
|
||||
pts = []
|
||||
for (fy, q) in tape:
|
||||
cfo, capex, rev = _ttm(discrete["cfo"], fy, q), _ttm(discrete["capex"], fy, q), _ttm(discrete["revenue"], fy, q)
|
||||
val = None if cfo is None or capex is None or not rev else (cfo - capex) / rev * 100.0
|
||||
pts.append(MetricPoint(_period_end(selected, fy, q), val))
|
||||
return _series(pts)
|
||||
|
||||
|
||||
def _instant_series(selected, tape, fn) -> MetricSeries:
|
||||
pts = [MetricPoint(_period_end(selected, fy, q), fn(selected.get((fy, _Q_TO_FP[q])))) for (fy, q) in tape]
|
||||
return _series(pts)
|
||||
|
||||
|
||||
def _leverage_series(selected, discrete, tape) -> MetricSeries:
|
||||
pts = []
|
||||
for (fy, q) in tape:
|
||||
row = selected.get((fy, _Q_TO_FP[q]))
|
||||
nd = _net_debt(row)
|
||||
op, da = _ttm(discrete["operating_income"], fy, q), _ttm(discrete["depreciation_amortization"], fy, q)
|
||||
ebitda = None if op is None or da is None else op + da
|
||||
# Null when EBITDA <= 0: a negative denominator would flip polarity and a
|
||||
# "lower is better" read would rank a distressed issuer as favorable.
|
||||
val = None if nd is None or ebitda is None or ebitda <= 0 else nd / ebitda
|
||||
pts.append(MetricPoint(_period_end(selected, fy, q), val))
|
||||
return _series(pts)
|
||||
|
||||
|
||||
def _share_change_series(selected, tape) -> MetricSeries:
|
||||
pts = []
|
||||
for (fy, q) in tape:
|
||||
cur = _shares(selected.get((fy, _Q_TO_FP[q])))
|
||||
prior = _shares(selected.get((fy - 1, _Q_TO_FP[q])))
|
||||
pts.append(MetricPoint(_period_end(selected, fy, q), _pct_change(cur, prior)))
|
||||
return _series(pts)
|
||||
|
||||
|
||||
def _guard_split_sensitive_metrics(metrics: dict[str, MetricSeries]) -> bool:
|
||||
"""Suppress historical comparisons likely distorted by a corporate action.
|
||||
|
||||
Company Facts has no point-in-time split factors. A large YoY share-count
|
||||
move can therefore make both the point-in-time share comparison and
|
||||
per-share EPS growth non-comparable. Keep the raw facts in snapshots, but
|
||||
expose nulls plus an explicit caveat in the user-facing derived series.
|
||||
|
||||
Returns True when the *latest* period is suspect, so callers can apply the
|
||||
same suppression to per-share scalars derived from that window.
|
||||
"""
|
||||
shares = metrics.get("share_count_change_yoy")
|
||||
eps = metrics.get("eps_growth_yoy")
|
||||
if shares is None or eps is None:
|
||||
return False
|
||||
|
||||
suspect_periods = {
|
||||
point.period_end
|
||||
for point in shares.history
|
||||
if point.value is not None
|
||||
and abs(point.value) >= SPLIT_SUSPECT_SHARE_CHANGE_PCT
|
||||
}
|
||||
if not suspect_periods:
|
||||
return False
|
||||
|
||||
latest_suspect = False
|
||||
for series in (shares, eps):
|
||||
latest_guarded = bool(
|
||||
series.history and series.history[-1].period_end in suspect_periods
|
||||
)
|
||||
latest_suspect = latest_suspect or latest_guarded
|
||||
for point in series.history:
|
||||
if point.period_end in suspect_periods:
|
||||
point.value = None
|
||||
series.value = series.history[-1].value if series.history else None
|
||||
if latest_guarded:
|
||||
series.caveat = SPLIT_SENSITIVE_CAVEAT
|
||||
return latest_suspect
|
||||
|
||||
|
||||
def _net_debt(row: Any) -> float | None:
|
||||
if row is None:
|
||||
return None
|
||||
cash = getattr(row, "cash_and_st_investments", None)
|
||||
debt = getattr(row, "total_debt", None)
|
||||
# Require BOTH components — treating a missing side as zero would produce a
|
||||
# partial, misleading value.
|
||||
if cash is None or debt is None:
|
||||
return None
|
||||
return debt - cash # positive = net debt
|
||||
|
||||
|
||||
def _shares(row: Any) -> float | None:
|
||||
return getattr(row, "shares_outstanding", None) if row is not None else None
|
||||
|
||||
|
||||
def _series(points: list[MetricPoint]) -> MetricSeries:
|
||||
value = points[-1].value if points else None
|
||||
return MetricSeries(value=value, history=points)
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Pure peer comparison for fundamentals (read-time).
|
||||
|
||||
Peers are tracked-universe issuers sharing the **first two SIC digits**,
|
||||
deduplicated by CIK (GOOG/GOOGL are one issuer, one observation). This module is
|
||||
the pure statistics core: given a subject value and the peer group's values for a
|
||||
metric, it returns median + polarity-aware favorable percentile + peer_count, or
|
||||
None when there are fewer than the minimum valid peers (the caller then omits the
|
||||
industry object entirely rather than show a misleading comparison).
|
||||
|
||||
Grouping (which issuers share a 2-digit SIC, CIK-dedup) is the API's job; this
|
||||
module only does the math. **Absolute net_debt is size-dependent and must not get
|
||||
a peer percentile** — leverage is compared via net_debt_to_ebitda.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
MIN_PEERS = 5
|
||||
|
||||
|
||||
def _finite(v: Any) -> bool:
|
||||
"""True for a finite number — excludes None, bool, NaN, ±inf (plan: null/invalid)."""
|
||||
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
|
||||
|
||||
# Metric -> is a higher value more favorable? (Peer-eligible metrics only;
|
||||
# absolute net_debt is intentionally absent — size-dependent.)
|
||||
HIGHER_IS_BETTER: dict[str, bool] = {
|
||||
"revenue_growth_yoy": True,
|
||||
"eps_growth_yoy": True,
|
||||
"operating_margin": True,
|
||||
"fcf_margin": True,
|
||||
"fcf_yield": True,
|
||||
"net_debt_to_ebitda": False, # lower leverage is better
|
||||
"pe": False, # cheaper is better
|
||||
"share_count_change_yoy": False, # dilution is bad
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class PeerStat:
|
||||
median: float
|
||||
favorable_percentile: int # 0-100, polarity-aware (higher = more favorable)
|
||||
peer_count: int # valid issuers in the group
|
||||
|
||||
|
||||
def peer_stat(
|
||||
subject: float | None,
|
||||
group_values: list[float | None],
|
||||
*,
|
||||
higher_is_better: bool,
|
||||
min_peers: int = MIN_PEERS,
|
||||
) -> PeerStat | None:
|
||||
"""Median + favorable percentile for ``subject`` within its group.
|
||||
|
||||
``group_values`` is every issuer's value for the metric (including the
|
||||
subject), CIK-deduplicated by the caller. Null/invalid (non-finite) values are
|
||||
excluded. Returns None when fewer than ``min_peers`` valid values exist, or
|
||||
the subject is null/invalid.
|
||||
|
||||
The percentile is a **tie-aware rank against the other issuers** —
|
||||
``(worse + 0.5·tied) / (peers − 1)`` — so a whole group of equal values maps
|
||||
to 50, not 100, and the median maps to 50.
|
||||
"""
|
||||
valid = [v for v in group_values if _finite(v)]
|
||||
if not _finite(subject) or len(valid) < min_peers:
|
||||
return None
|
||||
median = statistics.median(valid)
|
||||
|
||||
others = valid.copy()
|
||||
try:
|
||||
others.remove(subject) # rank the subject against the OTHER issuers
|
||||
except ValueError:
|
||||
pass
|
||||
denom = len(others)
|
||||
if denom == 0:
|
||||
return None
|
||||
if higher_is_better:
|
||||
worse = sum(1 for v in others if v < subject)
|
||||
else:
|
||||
worse = sum(1 for v in others if v > subject)
|
||||
tied = sum(1 for v in others if v == subject)
|
||||
percentile = round((worse + 0.5 * tied) / denom * 100)
|
||||
return PeerStat(median=median, favorable_percentile=percentile, peer_count=len(valid))
|
||||
|
||||
|
||||
def peer_stat_for(
|
||||
metric_key: str, subject: float | None, group_values: list[float | None], **kwargs
|
||||
) -> PeerStat | None:
|
||||
"""Convenience wrapper that looks up polarity by metric key. Returns None for
|
||||
metrics not eligible for peer comparison (e.g. absolute net_debt)."""
|
||||
if metric_key not in HIGHER_IS_BETTER:
|
||||
return None
|
||||
return peer_stat(
|
||||
subject, group_values, higher_is_better=HIGHER_IS_BETTER[metric_key], **kwargs
|
||||
)
|
||||
|
||||
|
||||
def two_digit_sic(sic: str | None) -> str | None:
|
||||
"""The 2-digit SIC prefix used for grouping, or None if unusable."""
|
||||
if not sic:
|
||||
return None
|
||||
digits = str(sic).strip()
|
||||
return digits[:2] if len(digits) >= 2 and digits[:2].isdigit() else None
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Actionability gate for incomplete SEC fundamentals."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import exists, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.data_import_run import DataImportRun
|
||||
from app.models.fundamental_snapshot import FundamentalSnapshot
|
||||
from app.models.sec_filing_gap import SecFilingGap
|
||||
from app.models.ticker import Ticker
|
||||
|
||||
_SEC_FORMS = ("10-K", "10-Q", "10-K/A", "10-Q/A")
|
||||
|
||||
# How recent the issuer's own newest filing must be for an *escalated* gap to
|
||||
# stop pausing setups. A gap pauses an issuer until it is either resolved or
|
||||
# superseded by a later ingested filing — which assumes the gap is temporary.
|
||||
# It is not always: SEC's per-company Company-Facts files can go stale
|
||||
# indefinitely (2026-08, 43 large caps whose Q2 10-Qs the frames API carried but
|
||||
# whose companyfacts files never received), and since the supersede rule needs a
|
||||
# *successfully ingested* later filing, a stale file also swallows the next
|
||||
# quarter. The pause is then open-ended rather than seasonal.
|
||||
#
|
||||
# So the pause hands off to the alert: once `filing_gap_aged` has escalated a gap
|
||||
# to an operator (`escalated_at`), the issuer resumes on the fundamentals it does
|
||||
# have — provided those are recent. An issuer with nothing this fresh has no
|
||||
# usable fundamentals at all and stays paused, which is the case the gate was
|
||||
# built for. The retry queue is untouched: `active_gaps` still returns these, so
|
||||
# the importer keeps retrying and a recovered filing still resolves normally.
|
||||
GAP_GATE_RECENT_FILING_DAYS = 180
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SetupQuality:
|
||||
eligible: bool
|
||||
code: str | None = None
|
||||
message: str | None = None
|
||||
|
||||
|
||||
async def active_gaps(
|
||||
db: AsyncSession,
|
||||
ciks: set[str] | None = None,
|
||||
) -> list[SecFilingGap]:
|
||||
"""Unresolved gaps that have not been superseded by a later filing."""
|
||||
matching_snapshot = exists().where(
|
||||
FundamentalSnapshot.accession == SecFilingGap.accession
|
||||
)
|
||||
gap_date = func.coalesce(
|
||||
SecFilingGap.index_date,
|
||||
func.date(SecFilingGap.first_seen_at),
|
||||
)
|
||||
later_snapshot = exists().where(
|
||||
FundamentalSnapshot.cik == SecFilingGap.cik,
|
||||
FundamentalSnapshot.form.in_(_SEC_FORMS),
|
||||
FundamentalSnapshot.filed_date > gap_date,
|
||||
)
|
||||
stmt = select(SecFilingGap).where(
|
||||
~matching_snapshot,
|
||||
~later_snapshot,
|
||||
)
|
||||
if ciks is not None:
|
||||
if not ciks:
|
||||
return []
|
||||
stmt = stmt.where(SecFilingGap.cik.in_(ciks))
|
||||
return list((await db.execute(stmt)).scalars().all())
|
||||
|
||||
|
||||
async def gap_exempt_ciks(
|
||||
db: AsyncSession, gaps: list[SecFilingGap]
|
||||
) -> set[str]:
|
||||
"""CIKs whose gaps have stopped pausing setups (see GAP_GATE_RECENT_FILING_DAYS).
|
||||
|
||||
Every one of a CIK's active gaps must be escalated: one fresh gap alongside an
|
||||
old one still means a filing we might yet ingest, which is worth pausing for.
|
||||
|
||||
Public because the importer alerts on this exact transition (a CIK dropping
|
||||
out of this set is a pause coming back on) and the rule must not exist twice.
|
||||
"""
|
||||
by_cik: dict[str, list[SecFilingGap]] = defaultdict(list)
|
||||
for gap in gaps:
|
||||
by_cik[gap.cik].append(gap)
|
||||
escalated = {
|
||||
cik
|
||||
for cik, items in by_cik.items()
|
||||
if all(gap.escalated_at is not None for gap in items)
|
||||
}
|
||||
if not escalated:
|
||||
return set()
|
||||
cutoff = (
|
||||
datetime.now(timezone.utc) - timedelta(days=GAP_GATE_RECENT_FILING_DAYS)
|
||||
).date()
|
||||
rows = await db.execute(
|
||||
select(FundamentalSnapshot.cik)
|
||||
.where(
|
||||
FundamentalSnapshot.cik.in_(escalated),
|
||||
FundamentalSnapshot.form.in_(_SEC_FORMS),
|
||||
FundamentalSnapshot.filed_date >= cutoff,
|
||||
)
|
||||
.distinct()
|
||||
)
|
||||
return set(rows.scalars())
|
||||
|
||||
|
||||
async def _latest_validation(db: AsyncSession) -> dict:
|
||||
payload = (
|
||||
await db.execute(
|
||||
select(DataImportRun.validation_json)
|
||||
.where(
|
||||
DataImportRun.source == "sec_facts",
|
||||
DataImportRun.validation_json.is_not(None),
|
||||
)
|
||||
.order_by(DataImportRun.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if not payload:
|
||||
return {}
|
||||
try:
|
||||
summary = json.loads(payload)
|
||||
except (TypeError, ValueError):
|
||||
return {}
|
||||
return summary if isinstance(summary, dict) else {}
|
||||
|
||||
|
||||
async def blocked_reasons_by_cik(
|
||||
db: AsyncSession,
|
||||
ciks: set[str] | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Current SEC blocker code by CIK; no historical audit scan."""
|
||||
if ciks is not None and not ciks:
|
||||
return {}
|
||||
|
||||
gaps = await active_gaps(db, ciks)
|
||||
# Escalated gaps on issuers that still have recent fundamentals no longer
|
||||
# pause setups, on either path below — the summary mirrors the same filings.
|
||||
exempt = await gap_exempt_ciks(db, gaps)
|
||||
reasons = {
|
||||
gap.cik: "sec_filing_gap" for gap in gaps if gap.cik not in exempt
|
||||
}
|
||||
summary = await _latest_validation(db)
|
||||
|
||||
def wanted(cik: str) -> bool:
|
||||
return ciks is None or cik in ciks
|
||||
|
||||
# New summaries carry the complete compact CIK set while the detailed lists
|
||||
# stay capped for audit readability. Detailed entries supply the reason.
|
||||
for cik in summary.get("setup_blocked_ciks") or []:
|
||||
normalized = str(cik) if cik else ""
|
||||
if normalized and wanted(normalized) and normalized not in exempt:
|
||||
reasons.setdefault(normalized, "sec_filing_gap")
|
||||
for item in summary.get("missing_xbrl") or []:
|
||||
normalized = str(item.get("cik") or "")
|
||||
if normalized and wanted(normalized) and normalized not in exempt:
|
||||
reasons.setdefault(normalized, "sec_filing_gap")
|
||||
for cik in summary.get("no_xbrl_ciks") or []:
|
||||
normalized = str(cik) if cik else ""
|
||||
if normalized and wanted(normalized):
|
||||
reasons[normalized] = "no_xbrl_filings"
|
||||
for item in summary.get("no_xbrl_filings") or []:
|
||||
normalized = str(item.get("cik") or "")
|
||||
if normalized and wanted(normalized):
|
||||
reasons[normalized] = "no_xbrl_filings"
|
||||
return reasons
|
||||
|
||||
|
||||
async def blocked_ciks(db: AsyncSession) -> set[str]:
|
||||
return set(await blocked_reasons_by_cik(db))
|
||||
|
||||
|
||||
async def blocked_ticker_ids(db: AsyncSession) -> set[int]:
|
||||
ciks = await blocked_ciks(db)
|
||||
if not ciks:
|
||||
return set()
|
||||
rows = await db.execute(select(Ticker.id).where(Ticker.cik.in_(ciks)))
|
||||
return {int(ticker_id) for ticker_id in rows.scalars()}
|
||||
|
||||
|
||||
async def ticker_quality(db: AsyncSession, symbol: str) -> SetupQuality:
|
||||
ticker = (
|
||||
await db.execute(
|
||||
select(Ticker).where(Ticker.symbol == symbol.strip().upper())
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if ticker is None or not ticker.cik:
|
||||
return SetupQuality(eligible=True)
|
||||
reason = (await blocked_reasons_by_cik(db, {ticker.cik})).get(ticker.cik)
|
||||
if reason == "no_xbrl_filings":
|
||||
return SetupQuality(
|
||||
eligible=False,
|
||||
code=reason,
|
||||
message=(
|
||||
"No SEC 10-K/10-Q is available for this registrant, so new setups "
|
||||
"are paused. New registrants clear automatically after their first "
|
||||
"filing; a successor shell needs an SEC CIK override."
|
||||
),
|
||||
)
|
||||
if reason:
|
||||
return SetupQuality(
|
||||
eligible=False,
|
||||
code=reason,
|
||||
message=(
|
||||
"A recent SEC filing is still being reconciled, so new setups are "
|
||||
"paused. The scheduled fundamentals import retries it automatically."
|
||||
),
|
||||
)
|
||||
return SetupQuality(eligible=True)
|
||||
|
||||
|
||||
async def ticker_is_eligible(db: AsyncSession, ticker_id: int) -> bool:
|
||||
cik = (
|
||||
await db.execute(select(Ticker.cik).where(Ticker.id == ticker_id))
|
||||
).scalar_one_or_none()
|
||||
if not cik:
|
||||
return True
|
||||
return cik not in await blocked_reasons_by_cik(db, {cik})
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Deterministic text 'reads' for the fundamentals panel (pure, one rule set).
|
||||
|
||||
The tape reads and the header sentence use identical outputs — no LLM, no new
|
||||
composite score. Thresholds are tunable named constants, not scattered literals
|
||||
(plan: ±2pp growth, ±1pp margins, ±1% dilution, 60/40 peer bands, ≥3 periods).
|
||||
|
||||
Consumers pass metric series (value + dated history, from
|
||||
``fundamentals_derivation``) and peer percentiles; these functions return short
|
||||
strings or None (render "—", no read).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from statistics import mean
|
||||
from typing import Any
|
||||
|
||||
MIN_PERIODS = 3
|
||||
GROWTH_ACCEL_PP = 2.0
|
||||
MARGIN_MOVE_PP = 1.0
|
||||
SHARE_DILUTION_PCT = 1.0
|
||||
PEER_FAVORABLE = 60
|
||||
PEER_ADVERSE = 40
|
||||
|
||||
|
||||
def _latest_run(history: list[Any]) -> list[float]:
|
||||
"""The consecutive non-null values ending at the latest point (oldest->newest).
|
||||
A null latest, or an internal gap, truncates the run — so a read never reflects
|
||||
a period whose displayed value is n/a."""
|
||||
run: list[float] = []
|
||||
for p in reversed(history):
|
||||
if p.value is None:
|
||||
break
|
||||
run.append(p.value)
|
||||
run.reverse()
|
||||
return run
|
||||
|
||||
|
||||
def growth_read(history: list[Any]) -> str | None:
|
||||
"""Change in a YoY-growth series: latest − prior. Needs >= 3 consecutive
|
||||
non-null values ending at the latest point."""
|
||||
vals = _latest_run(history)
|
||||
if len(vals) < MIN_PERIODS:
|
||||
return None
|
||||
delta = vals[-1] - vals[-2]
|
||||
if delta >= GROWTH_ACCEL_PP:
|
||||
return "accelerating"
|
||||
if delta <= -GROWTH_ACCEL_PP:
|
||||
return "decelerating"
|
||||
return "steady"
|
||||
|
||||
|
||||
def margin_read(history: list[Any]) -> str | None:
|
||||
"""Latest margin vs the mean of prior periods (pp). Needs >= 3 consecutive
|
||||
non-null values ending at the latest point."""
|
||||
vals = _latest_run(history)
|
||||
if len(vals) < MIN_PERIODS:
|
||||
return None
|
||||
delta = vals[-1] - mean(vals[:-1])
|
||||
if delta >= MARGIN_MOVE_PP:
|
||||
return "improving"
|
||||
if delta <= -MARGIN_MOVE_PP:
|
||||
return "deteriorating"
|
||||
return "stable"
|
||||
|
||||
|
||||
def share_count_read(value: float | None) -> str | None:
|
||||
"""Share-count YoY %: >+1% dilution, <-1% buying back, else flat."""
|
||||
if value is None:
|
||||
return None
|
||||
if value > SHARE_DILUTION_PCT:
|
||||
return f"{value:.1f}% dilution"
|
||||
if value < -SHARE_DILUTION_PCT:
|
||||
return "buying back"
|
||||
return "flat"
|
||||
|
||||
|
||||
def peer_read(metric_key: str, favorable_percentile: int | None) -> str | None:
|
||||
"""Peer-relative read for a metric, polarity already baked into the
|
||||
percentile (higher = more favorable)."""
|
||||
if favorable_percentile is None:
|
||||
return None
|
||||
if favorable_percentile >= PEER_FAVORABLE:
|
||||
return _FAVORABLE.get(metric_key, "above peers")
|
||||
if favorable_percentile <= PEER_ADVERSE:
|
||||
return _ADVERSE.get(metric_key, "below peers")
|
||||
return "in line"
|
||||
|
||||
|
||||
_FAVORABLE = {
|
||||
"pe": "attractively valued",
|
||||
"fcf_yield": "above peers",
|
||||
"net_debt_to_ebitda": "conservative leverage",
|
||||
}
|
||||
_ADVERSE = {
|
||||
"pe": "priced above peers",
|
||||
"fcf_yield": "below peers",
|
||||
"net_debt_to_ebitda": "elevated leverage",
|
||||
}
|
||||
|
||||
|
||||
def header_sentence(
|
||||
growth: str | None, margin: str | None, valuation: str | None
|
||||
) -> str:
|
||||
"""Join the growth / margin / peer-valuation reads with ' · ', omitting
|
||||
segments with no read. Segment sources are fixed by the caller (growth =
|
||||
revenue-growth read, margin = operating-margin read, valuation = P/E peer
|
||||
read falling back to FCF yield)."""
|
||||
parts = []
|
||||
if growth:
|
||||
parts.append(f"growth {growth}")
|
||||
if margin:
|
||||
parts.append(f"margins {margin}")
|
||||
if valuation:
|
||||
parts.append(f"valuation {valuation}")
|
||||
return " · ".join(parts)
|
||||
@@ -28,6 +28,7 @@ MIN_BARS: dict[str, int] = {
|
||||
"atr": 15,
|
||||
"volume_profile": 20,
|
||||
"pivot_points": 5,
|
||||
"fip_id": 253, # 12-1 formation: need index i-252
|
||||
}
|
||||
|
||||
DEFAULT_PERIODS: dict[str, int] = {
|
||||
@@ -256,6 +257,12 @@ def compute_volume_profile(
|
||||
) -> dict[str, Any]:
|
||||
"""Compute Volume Profile: POC, Value Area, HVN, LVN.
|
||||
|
||||
Volume is assigned to the bin containing each bar's **close** (no
|
||||
double-counting across the high–low span).
|
||||
|
||||
HVN = local peaks in the volume histogram (not every bin above mean).
|
||||
LVN = local valleys in the histogram.
|
||||
|
||||
Score: proximity of latest close to POC (closer = higher).
|
||||
"""
|
||||
n = len(closes)
|
||||
@@ -275,14 +282,18 @@ def compute_volume_profile(
|
||||
price_min + (i + 0.5) * bin_width for i in range(num_bins)
|
||||
]
|
||||
|
||||
# Assign each bar's full volume to the close's bin only.
|
||||
for i in range(n):
|
||||
# Distribute volume across bins the bar spans
|
||||
bar_low, bar_high = lows[i], highs[i]
|
||||
for b in range(num_bins):
|
||||
bl = price_min + b * bin_width
|
||||
bh = bl + bin_width
|
||||
if bar_high >= bl and bar_low <= bh:
|
||||
bins[b] += volumes[i]
|
||||
c = closes[i]
|
||||
if c <= price_min:
|
||||
b = 0
|
||||
elif c >= price_max:
|
||||
b = num_bins - 1
|
||||
else:
|
||||
b = int((c - price_min) / bin_width)
|
||||
if b >= num_bins:
|
||||
b = num_bins - 1
|
||||
bins[b] += volumes[i]
|
||||
|
||||
total_vol = sum(bins)
|
||||
if total_vol == 0:
|
||||
@@ -304,10 +315,17 @@ def compute_volume_profile(
|
||||
va_low = round(price_min + min(va_indices) * bin_width, 4)
|
||||
va_high = round(price_min + (max(va_indices) + 1) * bin_width, 4)
|
||||
|
||||
# HVN / LVN: bins above/below average volume
|
||||
# HVN / LVN: local peaks / valleys (require above/below mean to skip noise)
|
||||
avg_vol = total_vol / num_bins
|
||||
hvn = [round(bin_prices[i], 4) for i in range(num_bins) if bins[i] > avg_vol]
|
||||
lvn = [round(bin_prices[i], 4) for i in range(num_bins) if bins[i] < avg_vol]
|
||||
hvn: list[float] = []
|
||||
lvn: list[float] = []
|
||||
for i in range(num_bins):
|
||||
left = bins[i - 1] if i > 0 else bins[i]
|
||||
right = bins[i + 1] if i < num_bins - 1 else bins[i]
|
||||
if bins[i] > left and bins[i] > right and bins[i] > avg_vol:
|
||||
hvn.append(round(bin_prices[i], 4))
|
||||
elif bins[i] < left and bins[i] < right and bins[i] < avg_vol:
|
||||
lvn.append(round(bin_prices[i], 4))
|
||||
|
||||
# Score: proximity of latest close to POC
|
||||
latest = closes[-1]
|
||||
@@ -333,10 +351,14 @@ def compute_pivot_points(
|
||||
lows: list[float],
|
||||
closes: list[float],
|
||||
window: int = 2,
|
||||
min_prominence: float | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Detect swing highs/lows as pivot points.
|
||||
|
||||
A swing high at index *i* means highs[i] >= all highs in [i-window, i+window].
|
||||
When *min_prominence* is set, only keep swings whose window range
|
||||
(max high − min low) is at least that amount — filters tiny noise fractals.
|
||||
|
||||
Score: based on number of pivots near current price.
|
||||
"""
|
||||
n = len(closes)
|
||||
@@ -349,12 +371,24 @@ def compute_pivot_points(
|
||||
swing_lows: list[float] = []
|
||||
|
||||
for i in range(window, n - window):
|
||||
lo = i - window
|
||||
hi = i + window + 1
|
||||
# Swing high
|
||||
if all(highs[i] >= highs[j] for j in range(i - window, i + window + 1)):
|
||||
swing_highs.append(round(highs[i], 4))
|
||||
if all(highs[i] >= highs[j] for j in range(lo, hi)):
|
||||
if min_prominence is None or min_prominence <= 0:
|
||||
swing_highs.append(round(highs[i], 4))
|
||||
else:
|
||||
depth = highs[i] - min(lows[j] for j in range(lo, hi))
|
||||
if depth >= min_prominence:
|
||||
swing_highs.append(round(highs[i], 4))
|
||||
# Swing low
|
||||
if all(lows[i] <= lows[j] for j in range(i - window, i + window + 1)):
|
||||
swing_lows.append(round(lows[i], 4))
|
||||
if all(lows[i] <= lows[j] for j in range(lo, hi)):
|
||||
if min_prominence is None or min_prominence <= 0:
|
||||
swing_lows.append(round(lows[i], 4))
|
||||
else:
|
||||
depth = max(highs[j] for j in range(lo, hi)) - lows[i]
|
||||
if depth >= min_prominence:
|
||||
swing_lows.append(round(lows[i], 4))
|
||||
|
||||
all_pivots = swing_highs + swing_lows
|
||||
latest = closes[-1]
|
||||
@@ -374,6 +408,88 @@ def compute_pivot_points(
|
||||
}
|
||||
|
||||
|
||||
# Path labels for display only. Calibrated on the ~505-name prod snapshot
|
||||
# (2026-07, n=502 with full history): empirical p25 ≈ −0.082, p75 ≈ +0.004,
|
||||
# mean ≈ −0.043. Paper-style |ID| ≳ 0.25 almost never appears in live equities
|
||||
# (only ~0.2% of names); real momentum winners cluster around −0.04…−0.12.
|
||||
# Thresholds are therefore ~quartile cutoffs, not ±0.25 textbook extremes.
|
||||
# Distribution is left-skewed (bullish sample → more "continuous" than "discrete"),
|
||||
# so the discrete band is not symmetric.
|
||||
FIP_PATH_CONTINUOUS_MAX = -0.08 # ~p25: smoother quartile
|
||||
FIP_PATH_DISCRETE_MIN = 0.00 # ~p75: less-continuous quartile
|
||||
|
||||
|
||||
def compute_fip_id(closes: list[float], as_of_index: int | None = None) -> dict[str, Any]:
|
||||
"""Da/Gurun/Warachka information discreteness over the 12-1 formation window.
|
||||
|
||||
Display / research context only — **not** used by the activation gate or
|
||||
production rank. Same window as residual 12-1 momentum: cumulative return
|
||||
from close[i-252] to close[i-21] (skip last month).
|
||||
|
||||
ID = sign(PRET) × (%neg − %pos)
|
||||
|
||||
Lower ID ⇒ smoother / more continuous path (for a winner: many small up days).
|
||||
Higher ID ⇒ jumpy / discrete path (few large moves).
|
||||
|
||||
Zero-return days count in neither numerator but remain in the denominator
|
||||
(paper definition). Quirk: a flat series with one big jump can still land
|
||||
near zero ("mixed") because zeros dilute %pos/%neg — faithful to the paper
|
||||
and to real equities (exact zero daily returns are rare). Synthetic jump
|
||||
tests assert ordering vs a steady climber, not the discrete label itself.
|
||||
"""
|
||||
i = len(closes) - 1 if as_of_index is None else as_of_index
|
||||
if i < 252 or closes[i - 252] <= 0 or closes[i - 21] <= 0:
|
||||
raise ValidationError(
|
||||
f"FIP ID requires at least 253 bars with positive formation closes, "
|
||||
f"got {len(closes)}"
|
||||
)
|
||||
pret = closes[i - 21] / closes[i - 252] - 1.0
|
||||
rets: list[float] = []
|
||||
for k in range(i - 251, i - 20):
|
||||
prev = closes[k - 1]
|
||||
if prev <= 0:
|
||||
raise ValidationError("FIP ID requires positive closes in the formation window")
|
||||
rets.append(closes[k] / prev - 1.0)
|
||||
if len(rets) < 200:
|
||||
raise ValidationError(
|
||||
f"FIP ID requires ≥200 daily returns in formation, got {len(rets)}"
|
||||
)
|
||||
n = len(rets)
|
||||
pct_pos = sum(1 for r in rets if r > 0) / n
|
||||
pct_neg = sum(1 for r in rets if r < 0) / n
|
||||
if pret > 0:
|
||||
sign = 1.0
|
||||
elif pret < 0:
|
||||
sign = -1.0
|
||||
else:
|
||||
sign = 0.0
|
||||
fip = sign * (pct_neg - pct_pos)
|
||||
# Map observed ID range (~[-0.3, 0.15]) loosely to 0–100 for the card chrome;
|
||||
# lower ID (smoother) → higher score. Display only.
|
||||
score = max(0.0, min(100.0, 50.0 * (1.0 - fip)))
|
||||
if fip <= FIP_PATH_CONTINUOUS_MAX:
|
||||
path = "continuous"
|
||||
path_label = "smooth grind (continuous information)"
|
||||
elif fip >= FIP_PATH_DISCRETE_MIN:
|
||||
path = "discrete"
|
||||
path_label = "jumpy path (discrete information)"
|
||||
else:
|
||||
path = "mixed"
|
||||
path_label = "mixed path"
|
||||
return {
|
||||
"fip_id": round(fip, 4),
|
||||
"pret_12_1": round(pret, 4),
|
||||
"pct_up_days": round(pct_pos * 100.0, 1),
|
||||
"pct_down_days": round(pct_neg * 100.0, 1),
|
||||
"formation_days": n,
|
||||
"path": path,
|
||||
"path_label": path_label,
|
||||
"display_only": True,
|
||||
"note": "Not used by the production gate or rank — context only.",
|
||||
"score": round(score, 4),
|
||||
}
|
||||
|
||||
|
||||
def compute_ema_cross(
|
||||
closes: list[float],
|
||||
short_period: int = 20,
|
||||
@@ -418,7 +534,15 @@ def compute_ema_cross(
|
||||
# Supported indicator types
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
INDICATOR_TYPES = {"adx", "ema", "rsi", "atr", "volume_profile", "pivot_points"}
|
||||
INDICATOR_TYPES = {
|
||||
"adx",
|
||||
"ema",
|
||||
"rsi",
|
||||
"atr",
|
||||
"volume_profile",
|
||||
"pivot_points",
|
||||
"fip_id",
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -481,6 +605,8 @@ async def get_indicator(
|
||||
result = compute_volume_profile(highs, lows, closes, volumes)
|
||||
elif indicator_type == "pivot_points":
|
||||
result = compute_pivot_points(highs, lows, closes)
|
||||
elif indicator_type == "fip_id":
|
||||
result = compute_fip_id(closes)
|
||||
else:
|
||||
raise ValidationError(f"Unknown indicator type: {indicator_type}")
|
||||
|
||||
|
||||
@@ -23,6 +23,15 @@ from app.services import price_service
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _refresh_structural_sr(db: AsyncSession, symbol: str) -> None:
|
||||
"""Rebuild Structural S/R after batch OHLCV writes (best-effort).
|
||||
|
||||
Price bars are already committed; an S/R failure must not discard the
|
||||
ingestion result. Shared with single-bar upsert via price_service.
|
||||
"""
|
||||
await price_service._refresh_structural_sr_best_effort(db, symbol)
|
||||
|
||||
|
||||
@dataclass
|
||||
class IngestionResult:
|
||||
"""Result of an ingestion run."""
|
||||
@@ -59,6 +68,19 @@ async def _get_ohlcv_bar_count(db: AsyncSession, ticker_id: int) -> int:
|
||||
return int(result.scalar() or 0)
|
||||
|
||||
|
||||
async def _get_latest_ohlcv_date(db: AsyncSession, ticker_id: int) -> date | None:
|
||||
result = await db.execute(
|
||||
select(func.max(OHLCVRecord.date)).where(OHLCVRecord.ticker_id == ticker_id)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
# If the provider returns no bars but our last stored session is older than this,
|
||||
# treat the run as stale (not "success / up to date"). Common causes: ticker
|
||||
# rename, delisting, or multi-day halt — SATS→ECHO is the canonical example.
|
||||
_STALE_OHLCV_GAP_DAYS = 5
|
||||
|
||||
|
||||
async def _update_progress(
|
||||
db: AsyncSession, ticker_id: int, last_date: date
|
||||
) -> None:
|
||||
@@ -78,6 +100,8 @@ async def fetch_and_ingest(
|
||||
symbol: str,
|
||||
start_date: date | None = None,
|
||||
end_date: date | None = None,
|
||||
*,
|
||||
refresh_sr: bool = True,
|
||||
) -> IngestionResult:
|
||||
"""Fetch OHLCV data from provider and upsert into Price Store.
|
||||
|
||||
@@ -107,7 +131,12 @@ async def fetch_and_ingest(
|
||||
if bar_count < minimum_backfill_bars:
|
||||
start_date = backfill_start
|
||||
elif progress is not None:
|
||||
start_date = progress.last_ingested_date + timedelta(days=1)
|
||||
# Re-fetch the latest stored session so an in-progress daily bar can
|
||||
# be overwritten as the market moves. Starting one day later makes
|
||||
# every subsequent intraday, near-close, and manual refresh skip
|
||||
# today's bar once the first partial snapshot has been stored.
|
||||
# The price-store upsert keeps this one-session overlap idempotent.
|
||||
start_date = progress.last_ingested_date
|
||||
else:
|
||||
start_date = backfill_start
|
||||
|
||||
@@ -145,8 +174,9 @@ async def fetch_and_ingest(
|
||||
|
||||
# Provider returned nothing. With no history at all this almost always means
|
||||
# the provider doesn't cover this symbol (Alpaca = US listings only) — surface
|
||||
# that instead of a misleading "success". With existing bars it just means
|
||||
# there were no new bars in the requested window.
|
||||
# that instead of a misleading "success". With recent history, an empty window
|
||||
# usually means weekends/holidays. With a multi-day gap, the symbol is likely
|
||||
# halted, delisted, or *renamed* (e.g. SATS → ECHO) and we must not claim success.
|
||||
if not records:
|
||||
existing = await _get_ohlcv_bar_count(db, ticker.id)
|
||||
if existing == 0:
|
||||
@@ -160,10 +190,24 @@ async def fetch_and_ingest(
|
||||
"(Alpaca serves US-listed securities only)."
|
||||
),
|
||||
)
|
||||
latest = await _get_latest_ohlcv_date(db, ticker.id)
|
||||
gap_days = (end_date - latest).days if latest is not None else None
|
||||
if gap_days is not None and gap_days > _STALE_OHLCV_GAP_DAYS:
|
||||
return IngestionResult(
|
||||
symbol=ticker.symbol,
|
||||
records_ingested=0,
|
||||
last_date=latest,
|
||||
status="stale",
|
||||
message=(
|
||||
f"No new bars since {latest.isoformat()} ({gap_days}d gap). "
|
||||
"The symbol may be halted, delisted, or renamed under a new ticker — "
|
||||
"check the listing and add/fetch the current symbol if it changed."
|
||||
),
|
||||
)
|
||||
return IngestionResult(
|
||||
symbol=ticker.symbol,
|
||||
records_ingested=0,
|
||||
last_date=None,
|
||||
last_date=latest,
|
||||
status="complete",
|
||||
message="Already up to date — no new bars.",
|
||||
)
|
||||
@@ -185,6 +229,8 @@ async def fetch_and_ingest(
|
||||
low=record.low,
|
||||
close=record.close,
|
||||
volume=record.volume,
|
||||
# One S/R rebuild at the end of the batch, not per bar.
|
||||
refresh_sr=False,
|
||||
)
|
||||
ingested_count += 1
|
||||
last_ingested = record.date
|
||||
@@ -193,12 +239,15 @@ async def fetch_and_ingest(
|
||||
await _update_progress(db, ticker.id, record.date)
|
||||
|
||||
except RateLimitError:
|
||||
# Mid-ingestion rate limit — return partial progress
|
||||
# Mid-ingestion rate limit — return partial progress after
|
||||
# refreshing S/R from whatever bars we already wrote.
|
||||
logger.warning(
|
||||
"Rate limited during ingestion for %s after %d records",
|
||||
ticker.symbol,
|
||||
ingested_count,
|
||||
)
|
||||
if ingested_count > 0 and refresh_sr:
|
||||
await _refresh_structural_sr(db, ticker.symbol)
|
||||
return IngestionResult(
|
||||
symbol=ticker.symbol,
|
||||
records_ingested=ingested_count,
|
||||
@@ -207,6 +256,28 @@ async def fetch_and_ingest(
|
||||
message=f"Rate limited. Ingested {ingested_count} records. Resume available.",
|
||||
)
|
||||
|
||||
if ingested_count > 0 and refresh_sr:
|
||||
await _refresh_structural_sr(db, ticker.symbol)
|
||||
|
||||
# Incremental fetches deliberately overlap the latest stored session so an
|
||||
# in-progress bar can be updated. A halted/delisted symbol can therefore
|
||||
# return one old bar forever; non-empty no longer means fresh. Judge stale
|
||||
# state from the newest stored session after the upserts instead.
|
||||
latest = await _get_latest_ohlcv_date(db, ticker.id)
|
||||
gap_days = (end_date - latest).days if latest is not None else None
|
||||
if gap_days is not None and gap_days > _STALE_OHLCV_GAP_DAYS:
|
||||
return IngestionResult(
|
||||
symbol=ticker.symbol,
|
||||
records_ingested=ingested_count,
|
||||
last_date=latest,
|
||||
status="stale",
|
||||
message=(
|
||||
f"No new bars since {latest.isoformat()} ({gap_days}d gap). "
|
||||
"The symbol may be halted, delisted, or renamed under a new ticker — "
|
||||
"check the listing and add/fetch the current symbol if it changed."
|
||||
),
|
||||
)
|
||||
|
||||
return IngestionResult(
|
||||
symbol=ticker.symbol,
|
||||
records_ingested=ingested_count,
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Single source for JobRunState reads/writes.
|
||||
|
||||
Mirrors ``settings_store``: ``record_finish`` never commits — the caller owns
|
||||
the transaction — and reads are batched so the admin listing stays one query.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Iterable
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.job_run_state import JobRunState
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _as_datetime(value: object) -> datetime | None:
|
||||
"""Runtime snapshots carry ISO strings; the column wants a datetime."""
|
||||
if isinstance(value, datetime):
|
||||
return value
|
||||
if isinstance(value, str) and value:
|
||||
try:
|
||||
return datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
async def get_map(db: AsyncSession, job_names: Iterable[str]) -> dict[str, JobRunState]:
|
||||
"""Return {job_name: row} for the given jobs that have ever finished.
|
||||
|
||||
``populate_existing`` because rows are written by core upserts, which leave
|
||||
any previously-loaded ORM instance in the identity map stale.
|
||||
"""
|
||||
result = await db.execute(
|
||||
select(JobRunState)
|
||||
.where(JobRunState.job_name.in_(list(job_names)))
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
return {row.job_name: row for row in result.scalars().all()}
|
||||
|
||||
|
||||
def _insert_for(db: AsyncSession):
|
||||
"""ON CONFLICT is dialect-specific; prod is Postgres, tests are SQLite."""
|
||||
dialect = db.get_bind().dialect.name
|
||||
return pg_insert if dialect == "postgresql" else sqlite_insert
|
||||
|
||||
|
||||
async def record_finish(db: AsyncSession, job_name: str, runtime: dict) -> None:
|
||||
"""Upsert the last-run row from a scheduler runtime snapshot.
|
||||
|
||||
Atomic, and newer-wins. Select-then-insert loses races that really happen
|
||||
here: pipelines are separate scheduler jobs that can overlap, and they share
|
||||
step ids -- data_collector belongs to all four. Two of them finishing that
|
||||
step together would both see no row and both insert, and the loser's
|
||||
IntegrityError is swallowed by the caller, so the run silently vanishes.
|
||||
|
||||
The ``where`` guard is the other half: without it a slower pipeline
|
||||
finishing an *older* run last would rewind finished_at and the status with
|
||||
it, so the panel would report a stale outcome as the latest one.
|
||||
"""
|
||||
finished_at = _as_datetime(runtime.get("finished_at")) or datetime.now(timezone.utc)
|
||||
message = runtime.get("message")
|
||||
now = datetime.now(timezone.utc)
|
||||
values = {
|
||||
"job_name": job_name,
|
||||
"status": str(runtime.get("status") or "completed"),
|
||||
"started_at": _as_datetime(runtime.get("started_at")),
|
||||
"finished_at": finished_at,
|
||||
"processed": runtime.get("processed"),
|
||||
"total": runtime.get("total"),
|
||||
"message": str(message)[:4000] if message else None,
|
||||
# Set explicitly: the model's onupdate hook does not fire for a core
|
||||
# INSERT ... ON CONFLICT DO UPDATE.
|
||||
"updated_at": now,
|
||||
}
|
||||
|
||||
statement = _insert_for(db)(JobRunState).values(**values)
|
||||
await db.execute(
|
||||
statement.on_conflict_do_update(
|
||||
index_elements=[JobRunState.job_name],
|
||||
set_={key: statement.excluded[key] for key in values if key != "job_name"},
|
||||
where=JobRunState.finished_at < statement.excluded.finished_at,
|
||||
)
|
||||
)
|
||||
@@ -18,6 +18,7 @@ from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.ticker import Ticker
|
||||
from app.services import ticker_service
|
||||
from app.services.price_service import query_ohlcv
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -34,6 +35,28 @@ STRATEGY_RANK_MOMENTUM_WEIGHT = 0.8
|
||||
STRATEGY_RANK_VOL_WEIGHT = 1.0 - STRATEGY_RANK_MOMENTUM_WEIGHT
|
||||
|
||||
|
||||
def blend_strategy_rank(
|
||||
momentum_percentile: float | None,
|
||||
volatility_percentile: float | None,
|
||||
*,
|
||||
momentum_weight: float = STRATEGY_RANK_MOMENTUM_WEIGHT,
|
||||
) -> float | None:
|
||||
"""80/20 production rank with mom-only fallback when vol is missing.
|
||||
|
||||
Live and backtest must share this policy: missing vol must not send a
|
||||
residual-qualified name to the bottom of the book (that was the old
|
||||
backtest behaviour when either leg was None).
|
||||
"""
|
||||
if momentum_percentile is not None and volatility_percentile is not None:
|
||||
vol_weight = 1.0 - momentum_weight
|
||||
return round(
|
||||
float(momentum_percentile) * momentum_weight
|
||||
+ float(volatility_percentile) * vol_weight,
|
||||
2,
|
||||
)
|
||||
return float(momentum_percentile) if momentum_percentile is not None else None
|
||||
|
||||
|
||||
def compute_12_1_momentum(closes: list[float]) -> float | None:
|
||||
"""Return over the window ending ~1 month ago, starting ~12 months ago.
|
||||
None when there isn't a full year of history."""
|
||||
@@ -100,41 +123,17 @@ async def _load_activation_benchmark(db: AsyncSession) -> dict[date, float]:
|
||||
|
||||
|
||||
async def compute_momentum_percentiles(db: AsyncSession) -> dict[str, float]:
|
||||
"""Compute each ticker's activation momentum rank.
|
||||
"""Momentum leg only — thin view of ``compute_activation_ranks``.
|
||||
|
||||
Production uses residual 12-1 momentum when benchmark data is available. If
|
||||
SPY data is absent, fall back to raw 12-1 momentum rather than disabling the
|
||||
scanner. Tickers without enough stock/benchmark history are absent.
|
||||
Prefer ``compute_activation_ranks`` in new code (includes vol + strategy_rank).
|
||||
Kept so tests/helpers that only need the residual/raw percentile map stay simple.
|
||||
"""
|
||||
result = await db.execute(select(Ticker).order_by(Ticker.symbol))
|
||||
tickers = list(result.scalars().all())
|
||||
|
||||
benchmark_closes = await _load_activation_benchmark(db)
|
||||
using_residual = len(benchmark_closes) >= _MOM_LOOKBACK
|
||||
|
||||
values: dict[str, float] = {}
|
||||
for ticker in tickers:
|
||||
try:
|
||||
records = await query_ohlcv(db, ticker.symbol)
|
||||
except Exception:
|
||||
logger.exception("Momentum fetch failed for %s", ticker.symbol)
|
||||
continue
|
||||
closes = [float(r.close) for r in records]
|
||||
value = (
|
||||
compute_residual_12_1_momentum([r.date for r in records], closes, benchmark_closes)
|
||||
if using_residual
|
||||
else compute_12_1_momentum(closes)
|
||||
)
|
||||
if value is not None:
|
||||
values[ticker.symbol] = value
|
||||
|
||||
percentiles = _percentiles(values)
|
||||
logger.info(json.dumps({
|
||||
"event": "momentum_ranked",
|
||||
"signal": "residual_12_1" if using_residual else "raw_12_1_fallback",
|
||||
"tickers": len(percentiles),
|
||||
}))
|
||||
return percentiles
|
||||
ranks = await compute_activation_ranks(db)
|
||||
return {
|
||||
sym: float(row["momentum_percentile"])
|
||||
for sym, row in ranks.items()
|
||||
if row.get("momentum_percentile") is not None
|
||||
}
|
||||
|
||||
|
||||
def compute_realized_vol_6m(closes: list[float]) -> float | None:
|
||||
@@ -171,7 +170,9 @@ async def compute_activation_ranks(db: AsyncSession) -> dict[str, dict[str, floa
|
||||
before scanning; the research backtest ranked each weekly setup-candidate
|
||||
cross-section, so this is the deliberate production approximation.
|
||||
"""
|
||||
result = await db.execute(select(Ticker).order_by(Ticker.symbol))
|
||||
result = await db.execute(
|
||||
ticker_service.active_only(select(Ticker).order_by(Ticker.symbol))
|
||||
)
|
||||
tickers = list(result.scalars().all())
|
||||
|
||||
benchmark_closes = await _load_activation_benchmark(db)
|
||||
@@ -204,19 +205,10 @@ async def compute_activation_ranks(db: AsyncSession) -> dict[str, dict[str, floa
|
||||
for sym in symbols:
|
||||
momentum_pct = momentum_percentiles.get(sym)
|
||||
vol_pct = vol_percentiles.get(sym)
|
||||
strategy_rank = (
|
||||
round(
|
||||
momentum_pct * STRATEGY_RANK_MOMENTUM_WEIGHT
|
||||
+ vol_pct * STRATEGY_RANK_VOL_WEIGHT,
|
||||
2,
|
||||
)
|
||||
if momentum_pct is not None and vol_pct is not None
|
||||
else momentum_pct
|
||||
)
|
||||
ranks[sym] = {
|
||||
"momentum_percentile": momentum_pct,
|
||||
"volatility_percentile": vol_pct,
|
||||
"strategy_rank": strategy_rank,
|
||||
"strategy_rank": blend_strategy_rank(momentum_pct, vol_pct),
|
||||
}
|
||||
|
||||
logger.info(json.dumps({
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
"""Trade setup outcome evaluation service.
|
||||
|
||||
Closes the feedback loop on R:R scanner setups: walks daily OHLCV bars
|
||||
after detection and records whether the stop or the target was hit first.
|
||||
Diagnostic barrier resolution for scanner setups: walks daily OHLCV bars
|
||||
after detection and records whether the gate target or the stop was hit first.
|
||||
|
||||
This is **not** the production exit model. Live paper trades and the portfolio
|
||||
monitor use ATR trail / max hold and never exit at the gate target. Track-record
|
||||
stats from this path measure gate-level plumbing, not ATR-trail book expectancy.
|
||||
|
||||
Outcome semantics (entry is the close at detection time, i.e. market entry):
|
||||
- target_hit: target reached before the stop
|
||||
- stop_hit: stop reached before the target
|
||||
- target_hit: gate target reached before the stop
|
||||
- stop_hit: stop reached before the gate target
|
||||
- ambiguous: stop AND target both within the same daily bar — with daily
|
||||
granularity the order is unknowable, counted as a loss in stats
|
||||
- expired: neither level hit within ``max_bars`` trading days
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import bisect
|
||||
import logging
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from sqlalchemy import and_, func, select
|
||||
@@ -20,6 +21,9 @@ from app.services.outcome_service import (
|
||||
Bar,
|
||||
evaluate_setup_against_bars,
|
||||
)
|
||||
from app.services.trade_policy import MANUAL_BOOK, SHADOW_BOOK, get_reentry_gate_locks
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Exit policy for OPEN paper trades (auto-close). Production defaults to the
|
||||
# July 2026 promoted strategy: initial stop + 3x ATR trailing stop, with a max
|
||||
@@ -318,6 +322,10 @@ async def create_trade(
|
||||
raise ValidationError("shares and entry_price must be positive")
|
||||
|
||||
ticker = await _get_ticker(db, symbol)
|
||||
if ticker.id in await get_reentry_gate_locks(db):
|
||||
raise ValidationError(
|
||||
f"{ticker.symbol} requires a post-stop gate reset before re-entry"
|
||||
)
|
||||
trade = PaperTrade(
|
||||
user_id=user_id,
|
||||
ticker_id=ticker.id,
|
||||
@@ -328,6 +336,9 @@ async def create_trade(
|
||||
target=target,
|
||||
status="open",
|
||||
opened_at=datetime.now(timezone.utc),
|
||||
# Near-close cutover era — Track Record must not mix with morning-scan
|
||||
# fills or future broker-routed fills when comparing to backtests.
|
||||
fill_mode="near_close",
|
||||
)
|
||||
db.add(trade)
|
||||
await db.commit()
|
||||
@@ -341,6 +352,7 @@ def _to_dict(
|
||||
current_price: float | None,
|
||||
benchmark_closes: dict[date, float] | None = None,
|
||||
trailing: tuple[float, float | None] | None = None,
|
||||
holding_sessions: tuple[int, int] | None = None,
|
||||
) -> dict:
|
||||
# For open trades, mark to market; for closed, the realized exit price.
|
||||
ref = current_price if trade.status == "open" else trade.close_price
|
||||
@@ -381,8 +393,11 @@ def _to_dict(
|
||||
"alpha_pct": alpha_pct,
|
||||
"alpha_usd": alpha_usd,
|
||||
"close_reason": trade.close_reason,
|
||||
"fill_mode": trade.fill_mode,
|
||||
"trailing_stop": trailing[0] if trailing else None,
|
||||
"trailing_distance_pct": trailing[1] if trailing else None,
|
||||
"sessions_held": holding_sessions[0] if holding_sessions else None,
|
||||
"sessions_remaining": holding_sessions[1] if holding_sessions else None,
|
||||
}
|
||||
|
||||
|
||||
@@ -390,7 +405,15 @@ async def list_trades(
|
||||
db: AsyncSession,
|
||||
user_id: int | None = None,
|
||||
status: str | None = None,
|
||||
book: str | None = MANUAL_BOOK,
|
||||
) -> list[dict]:
|
||||
"""Trades for the UI. Defaults to the discretionary book.
|
||||
|
||||
Shadow trades are attached to a user row for FK reasons only — they are not
|
||||
that person's decisions. Listing them alongside manual trades would mix two
|
||||
different books in one P&L and let the autonomous record be edited by hand.
|
||||
Pass ``book=None`` to deliberately span both.
|
||||
"""
|
||||
stmt = (
|
||||
select(PaperTrade, Ticker.symbol)
|
||||
.join(Ticker, PaperTrade.ticker_id == Ticker.id)
|
||||
@@ -399,6 +422,8 @@ async def list_trades(
|
||||
stmt = stmt.where(PaperTrade.user_id == user_id)
|
||||
if status is not None:
|
||||
stmt = stmt.where(PaperTrade.status == status)
|
||||
if book is not None:
|
||||
stmt = stmt.where(PaperTrade.book == book)
|
||||
stmt = stmt.order_by(PaperTrade.opened_at.desc())
|
||||
|
||||
rows = (await db.execute(stmt)).all()
|
||||
@@ -413,6 +438,35 @@ async def list_trades(
|
||||
# Current trailing-stop level + distance for open trades (when a trailing
|
||||
# policy is active).
|
||||
policy = await get_exit_policy(db)
|
||||
holding_sessions: dict[int, tuple[int, int]] = {}
|
||||
if policy["mode"] in ("time", "atr_trailing"):
|
||||
hold_days = int(policy["hold_days"])
|
||||
open_trades = [trade for trade, _ in rows if trade.status == "open"]
|
||||
if open_trades:
|
||||
ticker_ids = {trade.ticker_id for trade in open_trades}
|
||||
earliest_opened = min(trade.opened_at.date() for trade in open_trades)
|
||||
session_rows = (
|
||||
await db.execute(
|
||||
select(OHLCVRecord.ticker_id, OHLCVRecord.date)
|
||||
.where(
|
||||
OHLCVRecord.ticker_id.in_(ticker_ids),
|
||||
OHLCVRecord.date > earliest_opened,
|
||||
)
|
||||
.order_by(OHLCVRecord.ticker_id, OHLCVRecord.date)
|
||||
)
|
||||
).all()
|
||||
dates_by_ticker: dict[int, list[date]] = {}
|
||||
for ticker_id, session_date in session_rows:
|
||||
dates_by_ticker.setdefault(int(ticker_id), []).append(session_date)
|
||||
for trade in open_trades:
|
||||
dates = dates_by_ticker.get(trade.ticker_id, [])
|
||||
held = len(dates) - bisect.bisect_right(
|
||||
dates, trade.opened_at.date()
|
||||
)
|
||||
# Do not clamp: a policy shortened below the current holding
|
||||
# period must remain visible as overdue until the exit pass runs.
|
||||
holding_sessions[trade.id] = (held, hold_days - held)
|
||||
|
||||
trailing_info: dict[int, tuple[float, float | None]] = {}
|
||||
if policy["mode"] == "trailing":
|
||||
trail_frac = policy["trailing_pct"] / 100.0
|
||||
@@ -461,7 +515,14 @@ async def list_trades(
|
||||
trailing_info[t.id] = (level, dist)
|
||||
|
||||
return [
|
||||
_to_dict(t, sym, prices.get(t.ticker_id), benchmark_closes, trailing_info.get(t.id))
|
||||
_to_dict(
|
||||
t,
|
||||
sym,
|
||||
prices.get(t.ticker_id),
|
||||
benchmark_closes,
|
||||
trailing_info.get(t.id),
|
||||
holding_sessions.get(t.id),
|
||||
)
|
||||
for t, sym in rows
|
||||
]
|
||||
|
||||
@@ -481,6 +542,13 @@ async def close_trade(
|
||||
trade = result.scalar_one_or_none()
|
||||
if trade is None:
|
||||
raise NotFoundError(f"Paper trade not found: {trade_id}")
|
||||
if trade.book == SHADOW_BOOK:
|
||||
# The shadow book's value is that no human touched it. A hand-closed
|
||||
# position would make its record something other than what the strategy
|
||||
# would have done; it exits only via the automatic exit policy.
|
||||
raise ValidationError(
|
||||
"Shadow book trades are closed by the exit policy, not by hand"
|
||||
)
|
||||
if trade.status == "closed":
|
||||
raise ValidationError("Trade is already closed")
|
||||
|
||||
@@ -681,6 +749,66 @@ def build_equity_curve(
|
||||
return out
|
||||
|
||||
|
||||
KEY_PERFORMANCE_START = "performance_start_date"
|
||||
|
||||
|
||||
async def get_performance_start(db: AsyncSession) -> date | None:
|
||||
"""Date the performance view starts from, or None for 'all history'.
|
||||
|
||||
The strategy has been revised repeatedly, so early trades were taken under
|
||||
rules that no longer exist. Pinning a start date keeps the comparison inside
|
||||
one regime instead of averaging across configurations that were replaced.
|
||||
"""
|
||||
raw = await settings_store.get_value(db, KEY_PERFORMANCE_START, "")
|
||||
if not raw or not str(raw).strip():
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(str(raw).strip())
|
||||
except ValueError:
|
||||
logger.warning("invalid %s: %r", KEY_PERFORMANCE_START, raw)
|
||||
return None
|
||||
|
||||
|
||||
def trade_r_multiple(trade, mark: float | None) -> float | None:
|
||||
"""Result in R — profit measured in units of the trade's own initial risk.
|
||||
|
||||
R is the only sizing-independent yardstick available here: the shadow book
|
||||
sizes at a fixed 1% of equity while manual trades were sized by hand, so
|
||||
currency P&L cannot compare them. Open trades are marked to ``mark``.
|
||||
"""
|
||||
risk_per_share = abs(trade.entry_price - trade.stop_loss)
|
||||
if risk_per_share <= 0:
|
||||
return None
|
||||
exit_price = trade.close_price if trade.status == "closed" else mark
|
||||
if exit_price is None:
|
||||
return None
|
||||
per_share = (
|
||||
exit_price - trade.entry_price
|
||||
if trade.direction == "long"
|
||||
else trade.entry_price - exit_price
|
||||
)
|
||||
return per_share / risk_per_share
|
||||
|
||||
|
||||
def book_stats(trades: list, marks: dict[int, float]) -> dict:
|
||||
"""Sizing-independent summary of one book: counts, win rate, R-multiples."""
|
||||
rs = [
|
||||
r
|
||||
for r in (trade_r_multiple(t, marks.get(t.ticker_id)) for t in trades)
|
||||
if r is not None
|
||||
]
|
||||
closed = [t for t in trades if t.status == "closed"]
|
||||
wins = [r for r in rs if r > 0]
|
||||
return {
|
||||
"trades": len(trades),
|
||||
"closed": len(closed),
|
||||
"open": len(trades) - len(closed),
|
||||
"win_rate": round(100.0 * len(wins) / len(rs), 1) if rs else None,
|
||||
"total_r": round(sum(rs), 2) if rs else 0.0,
|
||||
"avg_r": round(sum(rs) / len(rs), 3) if rs else None,
|
||||
}
|
||||
|
||||
|
||||
async def equity_curve(db: AsyncSession, user_id: int) -> list[dict]:
|
||||
"""Equity-curve series for a user's paper book (empty without benchmark data)."""
|
||||
trades = (
|
||||
@@ -705,3 +833,118 @@ async def equity_curve(db: AsyncSession, user_id: int) -> list[dict]:
|
||||
for tid, day, close in rows.all():
|
||||
ticker_closes.setdefault(tid, {})[day] = float(close)
|
||||
return build_equity_curve(list(trades), ticker_closes, benchmark_closes)
|
||||
|
||||
|
||||
def _cumulative_pnl(trades: list, ticker_closes: dict, days: list[date]) -> list[float]:
|
||||
"""Cumulative realized + mark-to-market P&L of one book on each day."""
|
||||
sorted_dates = {tid: sorted(c) for tid, c in ticker_closes.items()}
|
||||
out: list[float] = []
|
||||
for d in days:
|
||||
total = 0.0
|
||||
for t in trades:
|
||||
if t.opened_at.date() > d:
|
||||
continue
|
||||
closed_on = (
|
||||
t.closed_at.date()
|
||||
if (t.status == "closed" and t.closed_at is not None)
|
||||
else None
|
||||
)
|
||||
if closed_on is not None and closed_on <= d and t.close_price is not None:
|
||||
ref = float(t.close_price)
|
||||
else:
|
||||
ref = _value_on_or_before(
|
||||
sorted_dates.get(t.ticker_id) or [],
|
||||
ticker_closes.get(t.ticker_id) or {},
|
||||
d,
|
||||
)
|
||||
if ref is None:
|
||||
continue
|
||||
per_share = (
|
||||
ref - t.entry_price if t.direction == "long" else t.entry_price - ref
|
||||
)
|
||||
total += per_share * t.shares
|
||||
out.append(round(total, 2))
|
||||
return out
|
||||
|
||||
|
||||
async def performance_summary(db: AsyncSession, user_id: int | None = None) -> dict:
|
||||
"""Shadow book vs discretionary book vs SPY, from the configured start date.
|
||||
|
||||
Currency P&L is reported per book but is *not* the comparison — the books
|
||||
size differently, so the honest read is the R-multiple stats. SPY is a plain
|
||||
buy-and-hold reference over the same window rather than a per-trade
|
||||
counterfactual, so one line serves both books.
|
||||
"""
|
||||
start = await get_performance_start(db)
|
||||
stmt = select(PaperTrade)
|
||||
if start is not None:
|
||||
stmt = stmt.where(func.date(PaperTrade.opened_at) >= start)
|
||||
if user_id is not None:
|
||||
# "Your picks" must be *yours*. The shadow book is a single autonomous
|
||||
# book with no owner, so it is never scoped to a user.
|
||||
stmt = stmt.where(
|
||||
(PaperTrade.book == SHADOW_BOOK) | (PaperTrade.user_id == user_id)
|
||||
)
|
||||
trades = list((await db.execute(stmt)).scalars().all())
|
||||
|
||||
benchmark_closes = await benchmark_service.load_benchmark_closes(db)
|
||||
empty = {
|
||||
"start_date": start.isoformat() if start else None,
|
||||
"series": [],
|
||||
"stats": {},
|
||||
}
|
||||
if not trades or not benchmark_closes:
|
||||
return empty
|
||||
|
||||
first = min(t.opened_at.date() for t in trades)
|
||||
if start is not None:
|
||||
first = max(first, start)
|
||||
days = [d for d in sorted(benchmark_closes) if d >= first]
|
||||
if not days:
|
||||
return empty
|
||||
|
||||
ticker_ids = {t.ticker_id for t in trades}
|
||||
rows = await db.execute(
|
||||
select(OHLCVRecord.ticker_id, OHLCVRecord.date, OHLCVRecord.close).where(
|
||||
OHLCVRecord.ticker_id.in_(ticker_ids), OHLCVRecord.date >= first
|
||||
)
|
||||
)
|
||||
ticker_closes: dict[int, dict[date, float]] = {}
|
||||
for tid, day, close in rows.all():
|
||||
ticker_closes.setdefault(tid, {})[day] = float(close)
|
||||
|
||||
books = {
|
||||
MANUAL_BOOK: [t for t in trades if (t.book or MANUAL_BOOK) == MANUAL_BOOK],
|
||||
SHADOW_BOOK: [t for t in trades if t.book == SHADOW_BOOK],
|
||||
}
|
||||
pnl = {
|
||||
name: _cumulative_pnl(book_trades, ticker_closes, days)
|
||||
for name, book_trades in books.items()
|
||||
}
|
||||
|
||||
bench_dates = sorted(benchmark_closes)
|
||||
spy0 = _value_on_or_before(bench_dates, benchmark_closes, days[0])
|
||||
spy_pct = [
|
||||
round(100.0 * (benchmark_closes[d] / spy0 - 1.0), 2) if spy0 else 0.0
|
||||
for d in days
|
||||
]
|
||||
|
||||
# Latest close per ticker, for marking open positions in the R stats.
|
||||
marks = {
|
||||
tid: closes[max(closes)] for tid, closes in ticker_closes.items() if closes
|
||||
}
|
||||
stats = {name: book_stats(bt, marks) for name, bt in books.items()}
|
||||
for name in books:
|
||||
stats[name]["pnl"] = pnl[name][-1] if pnl[name] else 0.0
|
||||
stats["spy"] = {"pct": spy_pct[-1] if spy_pct else 0.0}
|
||||
|
||||
series = [
|
||||
{
|
||||
"date": d.isoformat(),
|
||||
"manual_pnl": pnl[MANUAL_BOOK][i],
|
||||
"shadow_pnl": pnl[SHADOW_BOOK][i],
|
||||
"spy_pct": spy_pct[i],
|
||||
}
|
||||
for i, d in enumerate(days)
|
||||
]
|
||||
return {"start_date": start.isoformat() if start else None, "series": series, "stats": stats}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Per-invocation identity for pipeline runs.
|
||||
|
||||
A pipeline invocation stamps a unique run id into the task context. The scan it
|
||||
runs records that id alongside its completion markers, and the shadow book
|
||||
requires an *exact* match before acting on the scan's batch.
|
||||
|
||||
This is what timestamp comparison cannot provide. A manually triggered scan and
|
||||
the scheduled near-close pipeline are separate APScheduler jobs, and
|
||||
``max_instances=1`` only serialises a job against itself — not two different
|
||||
jobs. So a manual scan can start just before the pipeline and finish just after
|
||||
it began, leaving a completion timestamp later than the pipeline's start even
|
||||
though its batch is unrelated. Matching on a run id generated by the pipeline,
|
||||
and stamped only by the scan running inside that pipeline, removes the ambiguity.
|
||||
|
||||
Lives in its own module so the scheduler (which sets the id), the scanner (which
|
||||
stamps it), and the shadow book (which checks it) can all import it without an
|
||||
import cycle.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextvars
|
||||
import uuid
|
||||
|
||||
_run_id: contextvars.ContextVar[str | None] = contextvars.ContextVar(
|
||||
"pipeline_run_id", default=None
|
||||
)
|
||||
|
||||
|
||||
def new_run_id() -> str:
|
||||
"""A fresh, collision-free run id."""
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
def current() -> str | None:
|
||||
"""Run id of the pipeline invocation on the current task, if any."""
|
||||
return _run_id.get()
|
||||
|
||||
|
||||
def bind(run_id: str) -> contextvars.Token:
|
||||
"""Set the current run id; pass the returned token to ``release``."""
|
||||
return _run_id.set(run_id)
|
||||
|
||||
|
||||
def release(token: contextvars.Token) -> None:
|
||||
"""Restore the previous run id (call in a finally)."""
|
||||
_run_id.reset(token)
|
||||
@@ -1,15 +1,20 @@
|
||||
"""Price Store service: upsert and query OHLCV records."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import insert_for_session
|
||||
from app.exceptions import NotFoundError, ValidationError
|
||||
from app.models.ohlcv import OHLCVRecord
|
||||
from app.models.ticker import Ticker
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _get_ticker(db: AsyncSession, symbol: str) -> Ticker:
|
||||
"""Look up a ticker by symbol. Raises NotFoundError if missing."""
|
||||
@@ -44,16 +49,27 @@ async def upsert_ohlcv(
|
||||
low: float,
|
||||
close: float,
|
||||
volume: int,
|
||||
*,
|
||||
refresh_sr: bool = True,
|
||||
) -> OHLCVRecord:
|
||||
"""Insert or update an OHLCV record for (ticker, date).
|
||||
|
||||
Validates business rules, resolves ticker, then uses
|
||||
ON CONFLICT DO UPDATE on the (ticker_id, date) unique constraint.
|
||||
|
||||
``refresh_sr`` (default True) recalculates persisted Structural S/R after
|
||||
the write so chart levels stay current. Batch ingestion passes
|
||||
``refresh_sr=False`` and refreshes once at the end of the ticker batch.
|
||||
|
||||
The OHLCV commit is authoritative: if S/R rebuild fails after a successful
|
||||
price write, the error is logged, the session is rolled back to clear
|
||||
poison, and the upsert still returns the persisted bar (caller can retry
|
||||
S/R via the scanner/ingestion pipeline).
|
||||
"""
|
||||
_validate_ohlcv(high, low, open_, close, volume, record_date)
|
||||
ticker = await _get_ticker(db, symbol)
|
||||
|
||||
stmt = pg_insert(OHLCVRecord).values(
|
||||
stmt = insert_for_session(db, OHLCVRecord).values(
|
||||
ticker_id=ticker.id,
|
||||
date=record_date,
|
||||
open=open_,
|
||||
@@ -64,7 +80,7 @@ async def upsert_ohlcv(
|
||||
created_at=datetime.utcnow(),
|
||||
)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
constraint="uq_ohlcv_ticker_date",
|
||||
index_elements=["ticker_id", "date"],
|
||||
set_={
|
||||
"open": stmt.excluded.open,
|
||||
"high": stmt.excluded.high,
|
||||
@@ -80,12 +96,36 @@ async def upsert_ohlcv(
|
||||
|
||||
record = result.scalar_one()
|
||||
|
||||
# TODO: Invalidate LRU cache entries for this ticker (Task 7.1)
|
||||
# TODO: Mark composite score as stale for this ticker (Task 10.1)
|
||||
from app.cache import indicator_cache
|
||||
|
||||
indicator_cache.invalidate_ticker(ticker.symbol)
|
||||
|
||||
if refresh_sr:
|
||||
await _refresh_structural_sr_best_effort(db, ticker.symbol)
|
||||
|
||||
return record
|
||||
|
||||
|
||||
async def _refresh_structural_sr_best_effort(db: AsyncSession, symbol: str) -> bool:
|
||||
"""Rebuild Structural S/R; never fail a successful OHLCV write.
|
||||
|
||||
Returns True on success. On failure rolls the session back so a later
|
||||
operation on the same session is not poisoned by the failed unit of work.
|
||||
"""
|
||||
from app.services.sr_service import recalculate_sr_levels
|
||||
|
||||
try:
|
||||
await recalculate_sr_levels(db, symbol)
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception("Structural S/R refresh failed for %s after OHLCV write", symbol)
|
||||
try:
|
||||
await db.rollback()
|
||||
except Exception:
|
||||
logger.exception("Session rollback after S/R failure also failed for %s", symbol)
|
||||
return False
|
||||
|
||||
|
||||
async def query_ohlcv(
|
||||
db: AsyncSession,
|
||||
symbol: str,
|
||||
@@ -97,13 +137,7 @@ async def query_ohlcv(
|
||||
Returns records sorted by date ascending.
|
||||
Raises NotFoundError if the ticker does not exist.
|
||||
"""
|
||||
normalised = symbol.strip().upper()
|
||||
cache = db.info.get("ohlcv_cache")
|
||||
cache_key = (normalised, start_date, end_date)
|
||||
if cache is not None and cache_key in cache:
|
||||
return list(cache[cache_key])
|
||||
|
||||
ticker = await _get_ticker(db, normalised)
|
||||
ticker = await _get_ticker(db, symbol)
|
||||
|
||||
stmt = select(OHLCVRecord).where(OHLCVRecord.ticker_id == ticker.id)
|
||||
if start_date is not None:
|
||||
@@ -113,7 +147,4 @@ async def query_ohlcv(
|
||||
stmt = stmt.order_by(OHLCVRecord.date.asc())
|
||||
|
||||
result = await db.execute(stmt)
|
||||
records = list(result.scalars().all())
|
||||
if cache is not None:
|
||||
cache[cache_key] = records
|
||||
return list(records)
|
||||
return list(result.scalars().all())
|
||||
|
||||
@@ -56,7 +56,12 @@ def _clamp(value: float, low: float, high: float) -> float:
|
||||
return max(low, min(high, value))
|
||||
|
||||
|
||||
def _zone_representative_levels(sr_levels: list[SRLevel], entry_price: float) -> list[Any]:
|
||||
def _zone_representative_levels(
|
||||
sr_levels: list[SRLevel],
|
||||
entry_price: float,
|
||||
*,
|
||||
strength_mode: str = "sum",
|
||||
) -> list[Any]:
|
||||
"""Collapse near-duplicate S/R levels into one representative per zone.
|
||||
|
||||
Targets are generated from these representatives, so a clustered wall (e.g.
|
||||
@@ -71,11 +76,25 @@ def _zone_representative_levels(sr_levels: list[SRLevel], entry_price: float) ->
|
||||
if not sr_levels or entry_price <= 0:
|
||||
return list(sr_levels)
|
||||
|
||||
level_dicts = [
|
||||
{"price_level": float(lv.price_level), "strength": int(lv.strength), "type": lv.type}
|
||||
for lv in sr_levels
|
||||
]
|
||||
zones = cluster_sr_zones(level_dicts, entry_price, tolerance=_SR_ZONE_TOLERANCE)
|
||||
level_dicts = []
|
||||
for lv in sr_levels:
|
||||
level_dicts.append({
|
||||
"price_level": float(lv.price_level),
|
||||
"strength": int(lv.strength),
|
||||
"type": lv.type,
|
||||
"detection_method": getattr(lv, "detection_method", "unknown"),
|
||||
"sources": list(getattr(lv, "sources", None) or [
|
||||
getattr(lv, "detection_method", "unknown")
|
||||
]),
|
||||
"rejection_count": int(getattr(lv, "rejection_count", 0) or 0),
|
||||
"last_rejection_age": getattr(lv, "last_rejection_age", None),
|
||||
})
|
||||
zones = cluster_sr_zones(
|
||||
level_dicts,
|
||||
entry_price,
|
||||
tolerance=_SR_ZONE_TOLERANCE,
|
||||
strength_mode=strength_mode,
|
||||
)
|
||||
|
||||
reps: list[Any] = []
|
||||
for zone in zones:
|
||||
@@ -94,6 +113,10 @@ def _zone_representative_levels(sr_levels: list[SRLevel], entry_price: float) ->
|
||||
price_level=float(near_edge),
|
||||
type=zone["type"],
|
||||
strength=int(zone["strength"]),
|
||||
detection_method=getattr(strongest, "detection_method", "unknown"),
|
||||
sources=list(zone.get("sources") or []),
|
||||
rejection_count=int(zone.get("rejection_count", 0)),
|
||||
last_rejection_age=zone.get("last_rejection_age"),
|
||||
)
|
||||
)
|
||||
return reps
|
||||
@@ -312,6 +335,15 @@ class TargetGenerator:
|
||||
"classification": "Moderate",
|
||||
"sr_level_id": int(level.id),
|
||||
"sr_strength": float(level.strength),
|
||||
"sr_sources": list(getattr(level, "sources", None) or [
|
||||
getattr(level, "detection_method", "unknown")
|
||||
]),
|
||||
"sr_rejection_count": int(
|
||||
getattr(level, "rejection_count", 0) or 0
|
||||
),
|
||||
"sr_last_rejection_age": getattr(
|
||||
level, "last_rejection_age", None
|
||||
),
|
||||
"quality": float(quality),
|
||||
}
|
||||
)
|
||||
@@ -581,12 +613,15 @@ def build_recommendation_snapshot(
|
||||
}
|
||||
|
||||
|
||||
PRIMARY_TARGET_MIN_RR = 1.5
|
||||
# Below this the target is a lottery ticket. Shared with the activation gate
|
||||
# (qualification.MIN_TARGET_PROBABILITY) so the primary selection and the gate
|
||||
# agree on what counts as a probability-backed target.
|
||||
PRIMARY_TARGET_MIN_PROBABILITY = MIN_TARGET_PROBABILITY
|
||||
|
||||
# Primary-target selector floor (independent of the live activation min_rr).
|
||||
# Live scanner and backtest setup replay must share this constant.
|
||||
PRIMARY_TARGET_MIN_RR = 1.5
|
||||
|
||||
|
||||
def _prune_floor_pinned_targets(targets: list[dict]) -> list[dict]:
|
||||
"""Keep only the nearest target pinned at the probability clamp floor.
|
||||
@@ -610,7 +645,7 @@ def _prune_floor_pinned_targets(targets: list[dict]) -> list[dict]:
|
||||
|
||||
def _select_primary_target(
|
||||
targets: list[dict],
|
||||
min_rr: float = PRIMARY_TARGET_MIN_RR,
|
||||
min_rr: float,
|
||||
min_probability: float = PRIMARY_TARGET_MIN_PROBABILITY,
|
||||
) -> dict | None:
|
||||
"""Primary = the most LIKELY target that still offers real asymmetry.
|
||||
@@ -651,6 +686,7 @@ async def enhance_trade_setup(
|
||||
sr_levels: list[SRLevel],
|
||||
sentiment_classification: str | None,
|
||||
atr_value: float,
|
||||
primary_min_rr: float,
|
||||
available_directions: set[str] | None = None,
|
||||
) -> TradeSetup:
|
||||
config = await get_recommendation_config(db)
|
||||
@@ -698,7 +734,7 @@ async def enhance_trade_setup(
|
||||
# _select_primary_target), not the old quality-score pick that ignored
|
||||
# probability. Sync the setup's headline target/rr_ratio so the chart, gate
|
||||
# and outcome eval all agree with the table's starred row.
|
||||
primary = _select_primary_target(targets)
|
||||
primary = _select_primary_target(targets, min_rr=primary_min_rr)
|
||||
if primary is not None:
|
||||
for target in targets:
|
||||
target["is_primary"] = target is primary
|
||||
|
||||
+1406
-462
File diff suppressed because it is too large
Load Diff
@@ -1,9 +1,8 @@
|
||||
"""R:R Scanner service.
|
||||
"""R:R scanner service.
|
||||
|
||||
Scans tracked tickers for asymmetric risk-reward trade setups.
|
||||
Long: target = nearest SR above, stop = entry - ATR × multiplier.
|
||||
Short: target = nearest SR below, stop = entry + ATR × multiplier.
|
||||
Filters by configurable R:R threshold (default 1.5).
|
||||
Scans tracked tickers for asymmetric risk-reward trade setups. Candidate
|
||||
targets come from a transient, volume-free proposal ladder; persisted S/R is
|
||||
reserved for human-facing charts and alerts. Stops remain ATR-based.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,8 +11,10 @@ import json
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import and_, func, select
|
||||
from sqlalchemy import and_, func, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.exceptions import NotFoundError
|
||||
@@ -23,12 +24,22 @@ from app.models.paper_trade import PaperTrade
|
||||
from app.models.score import CompositeScore, DimensionScore
|
||||
from app.models.sentiment import SentimentScore
|
||||
from app.models.signal_context_snapshot import SignalContextSnapshot
|
||||
from app.models.sr_level import SRLevel
|
||||
from app.models.ticker import Ticker
|
||||
from app.models.trade_setup import TradeSetup
|
||||
from app.services.indicator_service import _extract_ohlcv, compute_atr
|
||||
from app.services import fundamentals_quality_service, system_event_service
|
||||
from app.services.price_service import query_ohlcv
|
||||
from app.services.qualification import setup_qualifies
|
||||
from app.services.sr_service import detect_gate_target_ladder
|
||||
from app.services import settings_store, ticker_service
|
||||
from app.services.trade_policy import (
|
||||
MANUAL_BOOK,
|
||||
SHADOW_BOOK,
|
||||
get_reentry_gate_locks,
|
||||
observe_reentry_gate_transitions,
|
||||
)
|
||||
from app.services.recommendation_service import (
|
||||
PRIMARY_TARGET_MIN_RR,
|
||||
_risk_level_from_conflicts,
|
||||
build_recommendation_snapshot,
|
||||
enhance_trade_setup,
|
||||
@@ -37,6 +48,14 @@ from app.services.recommendation_service import (
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Markers of the most recent *successful* scan, written together only when
|
||||
# scan_all_tickers completes. COMPLETED gives its freshness; RUN_ID identifies
|
||||
# the run — the same id stamped on every setup row it produced. The shadow book
|
||||
# matches RUN_ID exactly and then selects setups by that id, so neither a
|
||||
# concurrent manual scan nor a stale prior run can be mistaken for it.
|
||||
KEY_LAST_SCAN_COMPLETED = "last_scan_run_completed_at"
|
||||
KEY_LAST_SCAN_RUN_ID = "last_scan_run_id"
|
||||
|
||||
STRATEGY_VERSION = "residual_highvol_80_20_atr_trail3_v1"
|
||||
|
||||
# A setup counts as live only while the daily scan keeps re-emitting it. The
|
||||
@@ -49,6 +68,28 @@ STRATEGY_VERSION = "residual_highvol_80_20_atr_trail3_v1"
|
||||
LIVE_SETUP_MAX_AGE_DAYS = 3
|
||||
|
||||
|
||||
def _materialize_gate_target_levels(
|
||||
highs: list[float],
|
||||
lows: list[float],
|
||||
closes: list[float],
|
||||
) -> list[Any]:
|
||||
"""Create transient level objects for target generation, never persistence."""
|
||||
detected = detect_gate_target_ladder(highs, lows, closes)
|
||||
return [
|
||||
SimpleNamespace(
|
||||
id=-(index + 1),
|
||||
price_level=float(level["price_level"]),
|
||||
type=str(level["type"]),
|
||||
strength=int(level["strength"]),
|
||||
detection_method=str(level.get("detection_method", "range_grid")),
|
||||
sources=list(level.get("sources") or ["range_grid"]),
|
||||
rejection_count=int(level.get("rejection_count", 0) or 0),
|
||||
last_rejection_age=level.get("last_rejection_age"),
|
||||
)
|
||||
for index, level in enumerate(detected)
|
||||
]
|
||||
|
||||
|
||||
async def _get_ticker(db: AsyncSession, symbol: str) -> Ticker:
|
||||
normalised = symbol.strip().upper()
|
||||
result = await db.execute(select(Ticker).where(Ticker.symbol == normalised))
|
||||
@@ -58,6 +99,28 @@ async def _get_ticker(db: AsyncSession, symbol: str) -> Ticker:
|
||||
return ticker
|
||||
|
||||
|
||||
async def _mark_ticker_scores_stale(db: AsyncSession, symbol: str) -> None:
|
||||
"""Prevent a failed refresh from being presented as a current signal."""
|
||||
result = await db.execute(
|
||||
select(Ticker.id).where(Ticker.symbol == symbol.strip().upper())
|
||||
)
|
||||
ticker_id = result.scalar_one_or_none()
|
||||
if ticker_id is None:
|
||||
raise NotFoundError(f"Ticker not found: {symbol.strip().upper()}")
|
||||
|
||||
await db.execute(
|
||||
update(DimensionScore)
|
||||
.where(DimensionScore.ticker_id == ticker_id)
|
||||
.values(is_stale=True)
|
||||
)
|
||||
await db.execute(
|
||||
update(CompositeScore)
|
||||
.where(CompositeScore.ticker_id == ticker_id)
|
||||
.values(is_stale=True)
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
def _compute_quality_score(
|
||||
rr: float,
|
||||
strength: int,
|
||||
@@ -116,8 +179,11 @@ async def _apply_live_recommendation_context(
|
||||
select(DimensionScore).where(DimensionScore.ticker_id.in_(ticker_ids))
|
||||
)
|
||||
dims_by_ticker: dict[int, dict[str, float]] = {}
|
||||
stale_score_ticker_ids: set[int] = set()
|
||||
for ds in dim_result.scalars().all():
|
||||
dims_by_ticker.setdefault(ds.ticker_id, {})[ds.dimension] = float(ds.score)
|
||||
if ds.is_stale:
|
||||
stale_score_ticker_ids.add(ds.ticker_id)
|
||||
|
||||
comp_result = await db.execute(
|
||||
select(CompositeScore)
|
||||
@@ -153,6 +219,18 @@ async def _apply_live_recommendation_context(
|
||||
live_row["composite_score"] = float(comp.score)
|
||||
live_row["context_as_of"]["score_computed_at"] = comp.computed_at
|
||||
|
||||
if (
|
||||
comp is None
|
||||
or comp.is_stale
|
||||
or ticker_id in stale_score_ticker_ids
|
||||
):
|
||||
live_row["confidence_score"] = None
|
||||
live_row["recommended_action"] = "NEUTRAL"
|
||||
live_row["reasoning"] = "Score refresh pending; recommendation withheld."
|
||||
live_row["risk_level"] = "High"
|
||||
live_rows.append(live_row)
|
||||
continue
|
||||
|
||||
dimension_scores = dims_by_ticker.get(ticker_id)
|
||||
sentiment = sentiments.get(ticker_id)
|
||||
if sentiment is not None:
|
||||
@@ -367,6 +445,77 @@ async def _create_signal_context_snapshots(
|
||||
)
|
||||
|
||||
|
||||
async def resolve_activation_ranks_for_symbol(
|
||||
db: AsyncSession,
|
||||
symbol: str,
|
||||
) -> dict[str, float | None]:
|
||||
"""Universe activation ranks for one symbol (manual single-ticker scans).
|
||||
|
||||
The daily ``scan_all_tickers`` path ranks the whole universe once and passes
|
||||
percentiles into ``scan_ticker``. Manual refresh must do the same: without
|
||||
``momentum_percentile`` the activation gate treats the setup as unranked and
|
||||
it silently drops out of qualified trades.
|
||||
|
||||
Prefer a fresh cross-sectional rank; if ranking fails or the symbol is
|
||||
missing from the universe slice, fall back to the most recent prior setup
|
||||
that still carries ranks so a refresh never zeroes the gate inputs.
|
||||
"""
|
||||
symbol_u = symbol.strip().upper()
|
||||
empty: dict[str, float | None] = {
|
||||
"momentum_percentile": None,
|
||||
"strategy_rank": None,
|
||||
"volatility_percentile": None,
|
||||
}
|
||||
|
||||
try:
|
||||
from app.services import momentum_service
|
||||
|
||||
ranks = await momentum_service.compute_activation_ranks(db)
|
||||
hit = ranks.get(symbol_u)
|
||||
if hit is not None and hit.get("momentum_percentile") is not None:
|
||||
return {
|
||||
"momentum_percentile": hit.get("momentum_percentile"),
|
||||
"strategy_rank": hit.get("strategy_rank"),
|
||||
"volatility_percentile": hit.get("volatility_percentile"),
|
||||
}
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Activation ranking failed for single-ticker scan of %s", symbol_u
|
||||
)
|
||||
|
||||
ticker_result = await db.execute(
|
||||
select(Ticker.id).where(Ticker.symbol == symbol_u)
|
||||
)
|
||||
ticker_id = ticker_result.scalar_one_or_none()
|
||||
if ticker_id is None:
|
||||
return empty
|
||||
|
||||
prev_result = await db.execute(
|
||||
select(TradeSetup)
|
||||
.where(
|
||||
TradeSetup.ticker_id == ticker_id,
|
||||
TradeSetup.momentum_percentile.is_not(None),
|
||||
)
|
||||
.order_by(TradeSetup.detected_at.desc(), TradeSetup.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
prev = prev_result.scalar_one_or_none()
|
||||
if prev is None:
|
||||
return empty
|
||||
|
||||
return {
|
||||
"momentum_percentile": (
|
||||
float(prev.momentum_percentile) if prev.momentum_percentile is not None else None
|
||||
),
|
||||
"strategy_rank": (
|
||||
float(prev.strategy_rank) if prev.strategy_rank is not None else None
|
||||
),
|
||||
"volatility_percentile": (
|
||||
float(prev.volatility_percentile) if prev.volatility_percentile is not None else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
async def scan_ticker(
|
||||
db: AsyncSession,
|
||||
symbol: str,
|
||||
@@ -375,15 +524,40 @@ async def scan_ticker(
|
||||
momentum_percentile: float | None = None,
|
||||
strategy_rank: float | None = None,
|
||||
volatility_percentile: float | None = None,
|
||||
primary_min_rr: float | None = None,
|
||||
gate_levels_override: list[Any] | None = None,
|
||||
scan_run_id: str | None = None,
|
||||
fundamentals_eligible: bool | None = None,
|
||||
) -> list[TradeSetup]:
|
||||
"""Scan a single ticker for trade setups meeting the R:R threshold.
|
||||
|
||||
``momentum_percentile`` is the ticker's residual 12-1 momentum activation
|
||||
rank across the universe (computed by the caller), stored on each setup so
|
||||
the activation gate can select the top slice. ``strategy_rank`` is the
|
||||
production ordering score used for top-pick ranking."""
|
||||
production ordering score used for top-pick ranking.
|
||||
|
||||
``primary_min_rr`` controls target selection only. Its 1.5 default is
|
||||
intentionally independent of the later activation floor (2.0 in the live
|
||||
Admin configuration). ``gate_levels_override`` is dependency injection for
|
||||
deterministic scanner tests; production builds the transient ladder from
|
||||
the ticker's OHLCV window.
|
||||
"""
|
||||
ticker = await _get_ticker(db, symbol)
|
||||
|
||||
if fundamentals_eligible is None:
|
||||
fundamentals_eligible = await fundamentals_quality_service.ticker_is_eligible(
|
||||
db, ticker.id
|
||||
)
|
||||
if not fundamentals_eligible:
|
||||
logger.info(
|
||||
"Skipping %s: unresolved or unavailable SEC fundamentals",
|
||||
ticker.symbol,
|
||||
)
|
||||
return []
|
||||
|
||||
if primary_min_rr is None:
|
||||
primary_min_rr = PRIMARY_TARGET_MIN_RR
|
||||
|
||||
records = await query_ohlcv(db, symbol)
|
||||
if not records or len(records) < 15:
|
||||
logger.info(
|
||||
@@ -406,21 +580,22 @@ async def scan_ticker(
|
||||
logger.info("Skipping %s: ATR is zero or negative", symbol)
|
||||
return []
|
||||
|
||||
sr_result = await db.execute(
|
||||
select(SRLevel).where(SRLevel.ticker_id == ticker.id)
|
||||
gate_levels = (
|
||||
list(gate_levels_override)
|
||||
if gate_levels_override is not None
|
||||
else _materialize_gate_target_levels(highs, lows, closes)
|
||||
)
|
||||
sr_levels = list(sr_result.scalars().all())
|
||||
|
||||
if not sr_levels:
|
||||
logger.info("Skipping %s: no SR levels available", symbol)
|
||||
if not gate_levels:
|
||||
logger.info("Skipping %s: no gate target levels available", symbol)
|
||||
return []
|
||||
|
||||
levels_above = sorted(
|
||||
[lv for lv in sr_levels if lv.price_level > entry_price],
|
||||
[lv for lv in gate_levels if lv.price_level > entry_price],
|
||||
key=lambda lv: lv.price_level,
|
||||
)
|
||||
levels_below = sorted(
|
||||
[lv for lv in sr_levels if lv.price_level < entry_price],
|
||||
[lv for lv in gate_levels if lv.price_level < entry_price],
|
||||
key=lambda lv: lv.price_level,
|
||||
reverse=True,
|
||||
)
|
||||
@@ -518,9 +693,10 @@ async def scan_ticker(
|
||||
ticker=ticker,
|
||||
setup=setup,
|
||||
dimension_scores=dimension_scores,
|
||||
sr_levels=sr_levels,
|
||||
sr_levels=gate_levels,
|
||||
sentiment_classification=sentiment_classification,
|
||||
atr_value=atr_value,
|
||||
primary_min_rr=primary_min_rr,
|
||||
available_directions=available_directions,
|
||||
)
|
||||
enhanced_setups.append(enhanced)
|
||||
@@ -529,6 +705,9 @@ async def scan_ticker(
|
||||
enhanced_setups.append(setup)
|
||||
|
||||
for setup in enhanced_setups:
|
||||
# Stamp identity after enhancement so it survives regardless of how the
|
||||
# enhancer rebuilds the row; the shadow book selects its batch by this.
|
||||
setup.scan_run_id = scan_run_id
|
||||
db.add(setup)
|
||||
|
||||
await db.commit()
|
||||
@@ -553,12 +732,51 @@ async def scan_all_tickers(
|
||||
``progress_callback(processed, total, current_symbol)`` is invoked as each
|
||||
ticker is scanned so callers (e.g. the scheduler) can surface live progress.
|
||||
"""
|
||||
result = await db.execute(select(Ticker).order_by(Ticker.symbol))
|
||||
tickers = list(result.scalars().all())
|
||||
total = len(tickers)
|
||||
# Ranking, score refresh, and setup detection repeatedly read the same
|
||||
# immutable OHLCV series during one scan. Scope the cache to this run only.
|
||||
db.info["ohlcv_cache"] = {}
|
||||
# Plain ids/strings, not Ticker instances: the rollbacks below expire any
|
||||
# ORM objects held across them, and touching an expired attribute afterwards
|
||||
# triggers sync lazy-loading, which raises on an AsyncSession.
|
||||
result = await db.execute(
|
||||
ticker_service.active_only(
|
||||
select(Ticker.id, Ticker.symbol).order_by(Ticker.symbol)
|
||||
)
|
||||
)
|
||||
ticker_rows = [(int(ticker_id), symbol) for ticker_id, symbol in result.all()]
|
||||
total = len(ticker_rows)
|
||||
|
||||
# Data-quality failures are not weak signals: they make a ticker ineligible.
|
||||
# Resolve once for the universe scan and pass the decision into scan_ticker.
|
||||
try:
|
||||
fundamentals_blocked_ids = (
|
||||
await fundamentals_quality_service.blocked_ticker_ids(db)
|
||||
)
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
logger.exception(
|
||||
"Could not resolve fundamentals quality; blocking this scan closed"
|
||||
)
|
||||
await system_event_service.log_event_standalone(
|
||||
severity="error",
|
||||
source="rr_scanner",
|
||||
code="fundamentals_quality_unavailable",
|
||||
message=(
|
||||
"The fundamentals quality gate could not be evaluated; the "
|
||||
"universe scan was blocked to avoid issuing unchecked setups."
|
||||
),
|
||||
dedup_key="rr_scanner:fundamentals_quality_unavailable",
|
||||
)
|
||||
fundamentals_blocked_ids = {ticker_id for ticker_id, _ in ticker_rows}
|
||||
|
||||
# Gate-reset observations must use the same runtime activation settings as
|
||||
# the live setup list. If the config cannot be loaded, scan normally but do
|
||||
# not mutate reset state from an evaluation whose rules are unknown.
|
||||
activation: dict | None = None
|
||||
try:
|
||||
from app.services.admin_service import get_activation_config
|
||||
|
||||
activation = await get_activation_config(db)
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
logger.exception("Activation config load for re-entry gate reset failed")
|
||||
|
||||
# Rank the universe up front so each new setup carries both the residual
|
||||
# activation gate percentile and the promoted production ordering score.
|
||||
@@ -569,43 +787,109 @@ async def scan_all_tickers(
|
||||
|
||||
ranks = await momentum_service.compute_activation_ranks(db)
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
logger.exception("Activation ranking refresh failed")
|
||||
ranks = {}
|
||||
|
||||
all_setups: list[TradeSetup] = []
|
||||
for index, ticker in enumerate(tickers):
|
||||
evaluated_ticker_ids: set[int] = set()
|
||||
qualified_ticker_ids: set[int] = set()
|
||||
gate_observation_started_at = datetime.now(timezone.utc)
|
||||
# One id for the whole run: stamped on every setup row and written to the
|
||||
# completion marker, so the shadow book can select this run's batch by
|
||||
# identity. From the pipeline when run as its scan step; a fresh id (never
|
||||
# matching any pipeline's) when triggered standalone.
|
||||
from app.services import pipeline_run
|
||||
|
||||
scan_run_id = pipeline_run.current() or pipeline_run.new_run_id()
|
||||
for index, (ticker_id, symbol) in enumerate(ticker_rows):
|
||||
if progress_callback is not None:
|
||||
progress_callback(index, total, ticker.symbol)
|
||||
progress_callback(index, total, symbol)
|
||||
if ticker_id in fundamentals_blocked_ids:
|
||||
logger.info(
|
||||
"Skipping %s: unresolved or unavailable SEC fundamentals",
|
||||
symbol,
|
||||
)
|
||||
continue
|
||||
# Refresh Structural S/R once, then scores. get_sr_levels is read-only;
|
||||
# without this recalculate the score path would see yesterday's zones.
|
||||
# A refresh failure still scans the ticker: qualification re-gates on
|
||||
# live scores at alert time, so a stale score is recoverable but a
|
||||
# skipped scan is not.
|
||||
try:
|
||||
# Refresh scores first so the scheduled scan works off current data.
|
||||
# Nothing else marks scores stale, so without this they'd never
|
||||
# update for tickers the user doesn't manually fetch.
|
||||
from app.services import scoring_service, sr_service
|
||||
|
||||
await sr_service.recalculate_sr_levels(db, symbol)
|
||||
await scoring_service.compute_all_dimensions(db, symbol)
|
||||
await scoring_service.compute_composite_score(db, symbol)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
logger.exception("Error refreshing scores for %s", symbol)
|
||||
try:
|
||||
from app.services import scoring_service
|
||||
|
||||
await scoring_service.compute_all_dimensions(db, ticker.symbol)
|
||||
await scoring_service.compute_composite_score(db, ticker.symbol)
|
||||
await _mark_ticker_scores_stale(db, symbol)
|
||||
except Exception:
|
||||
logger.exception("Error refreshing scores for %s", ticker.symbol)
|
||||
await db.rollback()
|
||||
logger.exception("Could not mark scores stale for %s", symbol)
|
||||
continue
|
||||
|
||||
try:
|
||||
setups = await scan_ticker(
|
||||
db, ticker.symbol, rr_threshold, atr_multiplier,
|
||||
momentum_percentile=(ranks.get(ticker.symbol) or {}).get("momentum_percentile"),
|
||||
strategy_rank=(ranks.get(ticker.symbol) or {}).get("strategy_rank"),
|
||||
volatility_percentile=(ranks.get(ticker.symbol) or {}).get("volatility_percentile"),
|
||||
db, symbol, rr_threshold, atr_multiplier,
|
||||
momentum_percentile=(ranks.get(symbol) or {}).get("momentum_percentile"),
|
||||
strategy_rank=(ranks.get(symbol) or {}).get("strategy_rank"),
|
||||
volatility_percentile=(ranks.get(symbol) or {}).get("volatility_percentile"),
|
||||
primary_min_rr=PRIMARY_TARGET_MIN_RR,
|
||||
scan_run_id=scan_run_id,
|
||||
fundamentals_eligible=True,
|
||||
)
|
||||
all_setups.extend(setups)
|
||||
if activation is not None:
|
||||
try:
|
||||
if any(setup_qualifies(setup, activation) for setup in setups):
|
||||
qualified_ticker_ids.add(ticker_id)
|
||||
evaluated_ticker_ids.add(ticker_id)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Gate-reset qualification observation failed for %s", symbol
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Error scanning ticker %s", ticker.symbol)
|
||||
await db.rollback()
|
||||
logger.exception("Error scanning ticker %s", symbol)
|
||||
|
||||
# scan_ticker commits successful setup writes. This final commit persists
|
||||
# refreshed scores for tickers that produced no setup or hit a scan error.
|
||||
await db.commit()
|
||||
if activation is not None:
|
||||
# Both books, from the same observation: gate-reset state is per book,
|
||||
# so observing only the manual book would leave shadow stop-outs stuck
|
||||
# with a fail timestamp that never requalifies — permanently ineligible.
|
||||
transitioned_ticker_ids: set[int] = set()
|
||||
for book in (MANUAL_BOOK, SHADOW_BOOK):
|
||||
transitioned_ticker_ids |= await observe_reentry_gate_transitions(
|
||||
db,
|
||||
evaluated_ticker_ids=evaluated_ticker_ids,
|
||||
qualified_ticker_ids=qualified_ticker_ids,
|
||||
observed_at=gate_observation_started_at,
|
||||
book=book,
|
||||
)
|
||||
await db.commit()
|
||||
if transitioned_ticker_ids:
|
||||
logger.info(
|
||||
"Updated post-stop gate-reset state for %d ticker(s)",
|
||||
len(transitioned_ticker_ids),
|
||||
)
|
||||
|
||||
db.info.pop("ohlcv_cache", None)
|
||||
if progress_callback is not None and total:
|
||||
progress_callback(total, total, "")
|
||||
|
||||
# Publish the run markers only now that the scan has completed: COMPLETED for
|
||||
# freshness and RUN_ID (the same id stamped on this run's setup rows) for
|
||||
# identity, in one commit. A hard failure above leaves the previous,
|
||||
# now-superseded, markers in place — so the shadow book will not match.
|
||||
await settings_store.upsert_setting(
|
||||
db, KEY_LAST_SCAN_COMPLETED, datetime.now(timezone.utc).isoformat()
|
||||
)
|
||||
await settings_store.upsert_setting(db, KEY_LAST_SCAN_RUN_ID, scan_run_id)
|
||||
await db.commit()
|
||||
|
||||
return all_setups
|
||||
|
||||
|
||||
@@ -617,6 +901,9 @@ async def get_trade_setups(
|
||||
symbol: str | None = None,
|
||||
live_recommendation: bool = False,
|
||||
exclude_open_trade_tickers: bool = False,
|
||||
exclude_open_trade_user_id: int | None = None,
|
||||
exclude_reentry_gate_locked_tickers: bool = False,
|
||||
include_reentry_gate_lock: bool = False,
|
||||
) -> list[dict]:
|
||||
"""Get latest stored trade setups, optionally filtered.
|
||||
|
||||
@@ -640,15 +927,55 @@ async def get_trade_setups(
|
||||
stmt = stmt.where(TradeSetup.confidence_score >= min_confidence)
|
||||
if recommended_action is not None and not live_recommendation:
|
||||
stmt = stmt.where(TradeSetup.recommended_action == recommended_action)
|
||||
excluded_ticker_ids: set[int] = set()
|
||||
reentry_gate_locks: dict[int, datetime] = {}
|
||||
try:
|
||||
excluded_ticker_ids.update(
|
||||
await fundamentals_quality_service.blocked_ticker_ids(db)
|
||||
)
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
logger.exception(
|
||||
"Could not resolve fundamentals quality; hiding actionable setups"
|
||||
)
|
||||
await system_event_service.log_event_standalone(
|
||||
severity="error",
|
||||
source="rr_scanner",
|
||||
code="fundamentals_quality_unavailable",
|
||||
message=(
|
||||
"The fundamentals quality gate could not be evaluated; actionable "
|
||||
"setups were hidden until the metadata check recovers."
|
||||
),
|
||||
dedup_key="rr_scanner:fundamentals_quality_unavailable",
|
||||
)
|
||||
return []
|
||||
if exclude_open_trade_tickers:
|
||||
open_trade_result = await db.execute(
|
||||
# Manual book only. The shadow book holds the *top-ranked* names by
|
||||
# construction, so letting its positions hide setups would leave the
|
||||
# discretionary list picking over leftovers — and would bias the very
|
||||
# shadow-vs-manual comparison the shadow book exists to measure.
|
||||
open_trade_stmt = (
|
||||
select(PaperTrade.ticker_id)
|
||||
.where(PaperTrade.status == "open")
|
||||
.where(PaperTrade.status == "open", PaperTrade.book == MANUAL_BOOK)
|
||||
.distinct()
|
||||
)
|
||||
open_ticker_ids = {ticker_id for ticker_id, in open_trade_result.all()}
|
||||
if open_ticker_ids:
|
||||
stmt = stmt.where(~TradeSetup.ticker_id.in_(open_ticker_ids))
|
||||
# Scope to one user for the personal setup list (don't hide a name just
|
||||
# because someone else holds it); leave it global for the Telegram
|
||||
# broadcast, which has no single owner.
|
||||
if exclude_open_trade_user_id is not None:
|
||||
open_trade_stmt = open_trade_stmt.where(
|
||||
PaperTrade.user_id == exclude_open_trade_user_id
|
||||
)
|
||||
open_trade_result = await db.execute(open_trade_stmt)
|
||||
excluded_ticker_ids.update(
|
||||
ticker_id for ticker_id, in open_trade_result.all()
|
||||
)
|
||||
if exclude_reentry_gate_locked_tickers or include_reentry_gate_lock:
|
||||
reentry_gate_locks = await get_reentry_gate_locks(db)
|
||||
if exclude_reentry_gate_locked_tickers:
|
||||
excluded_ticker_ids.update(reentry_gate_locks)
|
||||
if excluded_ticker_ids:
|
||||
stmt = stmt.where(~TradeSetup.ticker_id.in_(excluded_ticker_ids))
|
||||
|
||||
stmt = stmt.order_by(TradeSetup.detected_at.desc(), TradeSetup.id.desc())
|
||||
|
||||
@@ -701,6 +1028,15 @@ async def get_trade_setups(
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
if include_reentry_gate_lock:
|
||||
ticker_by_setup_id = {
|
||||
setup.id: setup.ticker_id for setup, _ in latest_rows
|
||||
}
|
||||
for row in rows_out:
|
||||
ticker_id = ticker_by_setup_id.get(row["id"])
|
||||
row["reentry_gate_reset_required"] = (
|
||||
ticker_id in reentry_gate_locks if ticker_id is not None else False
|
||||
)
|
||||
return rows_out
|
||||
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ from app.database import insert_for_session
|
||||
from app.exceptions import NotFoundError, ValidationError
|
||||
from app.models.score import CompositeScore, DimensionScore
|
||||
from app.models.ticker import Ticker
|
||||
from app.services import settings_store
|
||||
from app.services import settings_store, ticker_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -497,8 +497,8 @@ async def _compute_fundamental_score(
|
||||
"reason": "Earnings surprise data not available",
|
||||
})
|
||||
|
||||
# Require at least two real metrics — a single available metric (e.g. only
|
||||
# market cap is free on FMP) does not make a meaningful fundamental score.
|
||||
# Require at least two real metrics — a single available metric (e.g. an
|
||||
# issuer with only a market cap) does not make a meaningful fundamental score.
|
||||
MIN_METRICS = 2
|
||||
if len(scores) < MIN_METRICS:
|
||||
unavailable.append({
|
||||
@@ -748,35 +748,24 @@ async def compute_composite_score(
|
||||
|
||||
# Persist composite score
|
||||
now = datetime.now(timezone.utc)
|
||||
comp_result = await db.execute(
|
||||
select(CompositeScore).where(CompositeScore.ticker_id == ticker.id)
|
||||
stmt = insert_for_session(db, CompositeScore).values(
|
||||
ticker_id=ticker.id,
|
||||
score=composite,
|
||||
is_stale=False,
|
||||
weights_json=json.dumps(weights),
|
||||
computed_at=now,
|
||||
)
|
||||
existing = comp_result.scalar_one_or_none()
|
||||
|
||||
if existing is not None:
|
||||
existing.score = composite
|
||||
existing.is_stale = False
|
||||
existing.weights_json = json.dumps(weights)
|
||||
existing.computed_at = now
|
||||
else:
|
||||
stmt = insert_for_session(db, CompositeScore).values(
|
||||
ticker_id=ticker.id,
|
||||
score=composite,
|
||||
is_stale=False,
|
||||
weights_json=json.dumps(weights),
|
||||
computed_at=now,
|
||||
)
|
||||
await db.execute(
|
||||
stmt.on_conflict_do_update(
|
||||
index_elements=["ticker_id"],
|
||||
set_={
|
||||
"score": stmt.excluded.score,
|
||||
"is_stale": False,
|
||||
"weights_json": stmt.excluded.weights_json,
|
||||
"computed_at": stmt.excluded.computed_at,
|
||||
},
|
||||
)
|
||||
await db.execute(
|
||||
stmt.on_conflict_do_update(
|
||||
index_elements=["ticker_id"],
|
||||
set_={
|
||||
"score": stmt.excluded.score,
|
||||
"is_stale": False,
|
||||
"weights_json": stmt.excluded.weights_json,
|
||||
"computed_at": stmt.excluded.computed_at,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
return composite, missing
|
||||
|
||||
@@ -894,7 +883,11 @@ async def get_rankings(db: AsyncSession) -> dict:
|
||||
Returns dict suitable for RankingResponse.
|
||||
"""
|
||||
weights = await _get_weights(db)
|
||||
tickers = (await db.execute(select(Ticker).order_by(Ticker.symbol))).scalars().all()
|
||||
tickers = (
|
||||
await db.execute(
|
||||
ticker_service.active_only(select(Ticker).order_by(Ticker.symbol))
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
async def _load_scores() -> tuple[dict[int, CompositeScore], dict[int, dict[str, DimensionScore]]]:
|
||||
comps = {
|
||||
@@ -958,7 +951,7 @@ async def update_weights(
|
||||
await _save_weights(db, full_weights)
|
||||
|
||||
# Recompute all composite scores
|
||||
result = await db.execute(select(Ticker))
|
||||
result = await db.execute(ticker_service.active_only(select(Ticker)))
|
||||
tickers = list(result.scalars().all())
|
||||
|
||||
for ticker in tickers:
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
"""Async SEC EDGAR client for the fundamentals importer (workstream A).
|
||||
|
||||
All access is batch (never at request time). This wraps the three SEC products
|
||||
the A3 design uses — `company_tickers.json`, `submissions/`, `companyfacts/`, and
|
||||
the daily filing index — behind one client that honors SEC's fair-access policy:
|
||||
|
||||
- an identifying ``User-Agent`` with a contact email on every request (config);
|
||||
- request spacing well under the 10 req/s limit;
|
||||
- exponential backoff + retry on 429;
|
||||
- **403 → alert and stop** (raise ``SecForbiddenError``), never a retry-loop — a
|
||||
403 means the UA or request pattern is wrong and retrying won't fix it. The one
|
||||
exception is S3's ``AccessDenied`` on an ``/Archives/`` path, which is how the
|
||||
bucket reports an absent file (``_is_absent_archive_key``).
|
||||
|
||||
Parsing lives here (index fixed-width, submissions pagination); DB writes and the
|
||||
snapshot mapping live in the importer. No conditional GETs — the companyfacts
|
||||
endpoint exposes no ETag/Last-Modified (verified), which is why the importer is
|
||||
daily-index driven rather than polling archives.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from app.config import settings
|
||||
from app.exceptions import ProviderError
|
||||
from app.services.earnings_alignment import normalise_symbol
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_WWW = "https://www.sec.gov"
|
||||
_DATA = "https://data.sec.gov"
|
||||
|
||||
# Resolve CA bundle for explicit httpx verify (matches app/providers/alpaca.py).
|
||||
_CA = os.environ.get("SSL_CERT_FILE", "")
|
||||
_CA_VERIFY: str | bool = _CA if _CA and Path(_CA).exists() else True
|
||||
|
||||
_FORMS_10 = frozenset({"10-K", "10-Q", "10-K/A", "10-Q/A"})
|
||||
|
||||
# Notification of removal from listing. "25" is issuer-filed, "25-NSE" exchange-
|
||||
# filed. The Form 15 family is deliberately absent: it ends a *reporting*
|
||||
# obligation and does not mean the security stopped trading.
|
||||
_DELISTING_FORMS = frozenset({"25", "25-NSE"})
|
||||
|
||||
# ``descriptionClassSecurity`` is free text ("Common Stock", "Class A Common
|
||||
# Stock, $0.01 par value", "6.25% Notes due 2030", "Warrants", "Depositary
|
||||
# Shares"). Only a common-equity class means the ticker itself stopped trading.
|
||||
_NON_COMMON_CLASS = re.compile(
|
||||
r"\b(note|bond|debenture|preferred|warrant|right|unit|depositary|"
|
||||
r"subordinated|debt|trust)s?\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _is_common_stock(description: str) -> bool:
|
||||
"""Does this Form 25 security class describe common equity?
|
||||
|
||||
Requires an explicit common-stock match AND no debt/preferred/warrant marker,
|
||||
so "Depositary Shares each representing 1/1000th of Preferred" cannot pass on
|
||||
the word "shares" alone. Unrecognised text is rejected — a symbol is retired
|
||||
on this answer, so ambiguity must not read as yes.
|
||||
"""
|
||||
if _NON_COMMON_CLASS.search(description):
|
||||
return False
|
||||
return re.search(r"\bcommon\s+(stock|share)", description, re.IGNORECASE) is not None
|
||||
|
||||
|
||||
class SecError(ProviderError):
|
||||
"""SEC request failed (403, exhausted 429/5xx, timeout, transport, parse)."""
|
||||
|
||||
|
||||
class SecForbiddenError(SecError):
|
||||
"""SEC returned 403 — User-Agent/pattern rejected. Alert and stop."""
|
||||
|
||||
|
||||
class SecNotFoundError(SecError):
|
||||
"""The resource does not exist (e.g. no daily index published for a day).
|
||||
|
||||
The *only* error a caller may treat as 'missing' — every other SecError
|
||||
(fair-access rejection, exhausted retries, 5xx, timeout) must propagate so a
|
||||
fetch failure is never mistaken for an empty result.
|
||||
|
||||
Raised for a 404, and for the one 403 that also means "absent": see
|
||||
``_is_absent_archive_key``."""
|
||||
|
||||
|
||||
def _is_absent_archive_key(url: str, resp: httpx.Response) -> bool:
|
||||
"""True when a 403 means "this file does not exist", not "you are blocked".
|
||||
|
||||
``www.sec.gov/Archives`` is served straight out of an S3 bucket that grants
|
||||
no ``s3:ListBucket``, so a missing key cannot be answered with 404 — S3
|
||||
returns **403 with its ``AccessDenied`` XML** instead. SEC publishes a daily
|
||||
index only for business days, so every weekend and market holiday inside an
|
||||
incremental walk lands on exactly this response (verified 2026-07-30:
|
||||
``form.20260725.idx``, a Saturday, 403s while the Friday and Monday files
|
||||
return 200 on the same User-Agent).
|
||||
|
||||
A genuine fair-access rejection is distinguishable and must stay fatal: it is
|
||||
SEC's WAF interstitial — ``text/html``, "Your Request Originates from an
|
||||
Undeclared Automated Tool" — and it is returned for files that *do* exist,
|
||||
on any path. Hence the narrow gate: the Archives prefix plus S3's own error
|
||||
document. Nothing else may be downgraded to "missing"."""
|
||||
try:
|
||||
parsed = httpx.URL(url)
|
||||
except (TypeError, ValueError): # pragma: no cover — url comes from us
|
||||
return False
|
||||
if parsed.host != "www.sec.gov" or not parsed.path.startswith("/Archives/"):
|
||||
return False
|
||||
if "xml" not in resp.headers.get("Content-Type", "").lower():
|
||||
return False
|
||||
try:
|
||||
return "<Code>AccessDenied</Code>" in resp.text
|
||||
except (UnicodeDecodeError, httpx.HTTPError): # pragma: no cover
|
||||
return False
|
||||
|
||||
|
||||
def _looks_like_contact_email(ua: str) -> bool:
|
||||
if "example.com" in ua.lower() or "set-a-real-email" in ua.lower():
|
||||
return False
|
||||
return re.search(r"[^@\s]+@[^@\s]+\.[^@\s]+", ua) is not None
|
||||
|
||||
|
||||
# SEC asks callers to stay well under 10 req/s; enforce a floor on real clients.
|
||||
_MIN_PROD_SPACING = 0.11
|
||||
|
||||
|
||||
def cik10(cik: int | str) -> str:
|
||||
"""Zero-pad a CIK to the 10-digit form SEC URLs use (320193 -> 0000320193)."""
|
||||
return str(int(cik)).zfill(10)
|
||||
|
||||
|
||||
class SecClient:
|
||||
"""Fair-access SEC HTTP client. Use as ``async with SecClient() as c:``."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
user_agent: str | None = None,
|
||||
spacing_seconds: float | None = None,
|
||||
max_retries: int | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
) -> None:
|
||||
self._ua = user_agent or settings.sec_user_agent
|
||||
self._spacing = (
|
||||
spacing_seconds if spacing_seconds is not None else settings.sec_request_spacing_seconds
|
||||
)
|
||||
self._max_retries = (
|
||||
max_retries if max_retries is not None else settings.sec_max_retries
|
||||
)
|
||||
self._timeout = timeout if timeout is not None else settings.sec_request_timeout_seconds
|
||||
self._transport = transport # injectable for tests
|
||||
self._client: httpx.AsyncClient | None = None
|
||||
self._lock = asyncio.Lock()
|
||||
self._last_request = 0.0
|
||||
|
||||
def _validate_fair_access(self) -> None:
|
||||
"""On a real (non-mocked) client, enforce SEC fair-access preconditions
|
||||
so we can't accidentally hammer SEC or get 403'd: a genuine contact-email
|
||||
User-Agent and a spacing floor. Mock transports skip this (tests use 0)."""
|
||||
if not _looks_like_contact_email(self._ua):
|
||||
raise SecError(
|
||||
"sec_user_agent must contain a real contact email (got "
|
||||
f"{self._ua!r}) — SEC fair-access requires it"
|
||||
)
|
||||
if self._spacing < _MIN_PROD_SPACING:
|
||||
raise SecError(
|
||||
f"sec_request_spacing_seconds {self._spacing} is below the "
|
||||
f"{_MIN_PROD_SPACING}s fair-access floor"
|
||||
)
|
||||
|
||||
async def __aenter__(self) -> "SecClient":
|
||||
if self._transport is None:
|
||||
self._validate_fair_access()
|
||||
self._client = httpx.AsyncClient(
|
||||
headers={"User-Agent": self._ua, "Accept-Encoding": "gzip, deflate"},
|
||||
timeout=self._timeout,
|
||||
verify=_CA_VERIFY,
|
||||
transport=self._transport,
|
||||
)
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc) -> None:
|
||||
if self._client is not None:
|
||||
await self._client.aclose()
|
||||
self._client = None
|
||||
|
||||
async def _throttle(self) -> None:
|
||||
async with self._lock:
|
||||
now = asyncio.get_event_loop().time()
|
||||
wait = self._spacing - (now - self._last_request)
|
||||
if wait > 0:
|
||||
await asyncio.sleep(wait)
|
||||
self._last_request = asyncio.get_event_loop().time()
|
||||
|
||||
async def _get(self, url: str) -> httpx.Response:
|
||||
assert self._client is not None, "use `async with SecClient()`"
|
||||
attempt = 0
|
||||
while True:
|
||||
await self._throttle()
|
||||
try:
|
||||
resp = await self._client.get(url)
|
||||
except (httpx.TimeoutException, httpx.TransportError) as exc:
|
||||
attempt += 1
|
||||
if attempt > self._max_retries:
|
||||
raise SecError(f"SEC network error for {url}: {exc}") from exc
|
||||
await asyncio.sleep(min(2.0**attempt, 30.0))
|
||||
continue
|
||||
|
||||
code = resp.status_code
|
||||
if code == 403:
|
||||
if _is_absent_archive_key(url, resp):
|
||||
raise SecNotFoundError(f"SEC 403/AccessDenied (absent) for {url}")
|
||||
raise SecForbiddenError(
|
||||
f"SEC 403 for {url} — User-Agent/pattern rejected; set a real "
|
||||
"sec_user_agent contact email"
|
||||
)
|
||||
if code == 404:
|
||||
raise SecNotFoundError(f"SEC 404 for {url}")
|
||||
# 429 and 5xx are transient — retry with backoff, honoring Retry-After.
|
||||
if code == 429 or 500 <= code < 600:
|
||||
attempt += 1
|
||||
if attempt > self._max_retries:
|
||||
raise SecError(f"SEC {code} after {self._max_retries} retries: {url}")
|
||||
delay = _retry_after_seconds(resp) or min(2.0**attempt, 30.0)
|
||||
logger.warning("SEC %d for %s — backoff %.1fs (attempt %d)", code, url, delay, attempt)
|
||||
await asyncio.sleep(delay)
|
||||
continue
|
||||
if code >= 400:
|
||||
raise SecError(f"SEC {code} for {url}")
|
||||
return resp
|
||||
|
||||
async def get_json(self, url: str) -> Any:
|
||||
return (await self._get(url)).json()
|
||||
|
||||
async def get_text(self, url: str) -> str:
|
||||
return (await self._get(url)).text
|
||||
|
||||
# -- domain fetchers ---------------------------------------------------
|
||||
|
||||
async def company_tickers(self) -> dict[str, int]:
|
||||
"""Map normalised ticker -> CIK (int). Multi-class tickers share a CIK."""
|
||||
data = await self.get_json(f"{_WWW}/files/company_tickers.json")
|
||||
out: dict[str, int] = {}
|
||||
for row in data.values():
|
||||
sym = normalise_symbol(row.get("ticker"))
|
||||
if sym:
|
||||
out[sym] = int(row["cik_str"])
|
||||
return out
|
||||
|
||||
async def submissions(self, cik: int | str, *, include_history: bool = False) -> dict[str, Any]:
|
||||
"""Issuer metadata + filing list.
|
||||
|
||||
``filings.recent`` caps at 1000; older accessions live in
|
||||
``filings.files[]`` shards. Only ``include_history=True`` (the one-time
|
||||
full backfill) fetches those shards — SIC refresh and incremental runs
|
||||
use the recent list alone and make no extra requests.
|
||||
"""
|
||||
base = await self.get_json(f"{_DATA}/submissions/CIK{cik10(cik)}.json")
|
||||
filings = _rows_from_arrays(base["filings"]["recent"])
|
||||
if include_history:
|
||||
for shard in base["filings"].get("files") or []:
|
||||
shard_data = await self.get_json(f"{_DATA}/submissions/{shard['name']}")
|
||||
filings.extend(_rows_from_arrays(shard_data))
|
||||
return {
|
||||
"cik": int(base["cik"]),
|
||||
"name": base.get("name"),
|
||||
"sic": base.get("sic"),
|
||||
"sic_description": base.get("sicDescription"),
|
||||
"fiscal_year_end": base.get("fiscalYearEnd"),
|
||||
"tickers": base.get("tickers") or [],
|
||||
"filings": filings,
|
||||
}
|
||||
|
||||
async def delisting_filing(
|
||||
self, cik: int | str, *, not_before: date | None = None
|
||||
) -> dict[str, Any] | None:
|
||||
"""Newest Form 25 removing this issuer's COMMON stock from listing.
|
||||
|
||||
Deliberately narrow, because the caller retires a symbol on the answer:
|
||||
|
||||
- **Form 25 only.** The Form 15 family terminates a reporting obligation
|
||||
(often just a class falling under the holder threshold) and is no
|
||||
evidence that trading stopped.
|
||||
- **Class-checked.** Form 25 is filed per security class — an issuer
|
||||
delisting its notes, preferred, warrants or an ADR class while the
|
||||
common keeps trading files one too. The filing's own
|
||||
``descriptionClassSecurity`` is what separates those, so the primary
|
||||
document is fetched and read rather than trusting the form type.
|
||||
- **``not_before``** rejects a historical filing for some long-gone
|
||||
class. Without it a 2019 Form 25 would retire a symbol whose bars
|
||||
stopped in 2026, and stamp 2019 as the date.
|
||||
|
||||
Anything unreadable — no primary document (pre-2009 filings have none),
|
||||
malformed XML, unrecognised class — returns ``None``. Fail closed: the
|
||||
caller keeps warning instead of retiring on a guess.
|
||||
|
||||
Reads ``filings.recent`` directly; ``submissions()`` keeps only the
|
||||
10-K/10-Q family, so Form 25 never survives its parser.
|
||||
"""
|
||||
base = await self.get_json(f"{_DATA}/submissions/CIK{cik10(cik)}.json")
|
||||
arrays = (base.get("filings") or {}).get("recent") or {}
|
||||
forms = arrays.get("form") or []
|
||||
dates = arrays.get("filingDate") or []
|
||||
accessions = arrays.get("accessionNumber") or []
|
||||
docs = arrays.get("primaryDocument") or []
|
||||
|
||||
candidates: list[tuple[date, str, str, str]] = []
|
||||
for i, form in enumerate(forms):
|
||||
if form not in _DELISTING_FORMS or i >= len(dates) or not dates[i]:
|
||||
continue
|
||||
try:
|
||||
filed = date.fromisoformat(dates[i])
|
||||
except ValueError:
|
||||
continue
|
||||
if not_before is not None and filed < not_before:
|
||||
continue
|
||||
if i >= len(accessions) or not accessions[i]:
|
||||
continue
|
||||
candidates.append((filed, form, accessions[i], docs[i] if i < len(docs) else ""))
|
||||
|
||||
for filed, form, accession, _doc in sorted(candidates, reverse=True):
|
||||
security = await self._form25_security_class(cik, accession)
|
||||
if security is None:
|
||||
continue
|
||||
if not _is_common_stock(security):
|
||||
continue
|
||||
return {
|
||||
"form": form,
|
||||
"filing_date": filed,
|
||||
"security_class": security,
|
||||
}
|
||||
return None
|
||||
|
||||
async def _form25_security_class(
|
||||
self, cik: int | str, accession: str
|
||||
) -> str | None:
|
||||
"""``descriptionClassSecurity`` from a Form 25's primary XML, or None.
|
||||
|
||||
The rendered ``primaryDocument`` is an XSL view of this file; the raw
|
||||
``primary_doc.xml`` beside it is the structured original.
|
||||
"""
|
||||
folder = accession.replace("-", "")
|
||||
url = (
|
||||
f"{_WWW}/Archives/edgar/data/{int(cik)}/{folder}/primary_doc.xml"
|
||||
)
|
||||
try:
|
||||
body = await self.get_text(url)
|
||||
except SecNotFoundError:
|
||||
return None
|
||||
match = re.search(
|
||||
r"<descriptionClassSecurity>(.*?)</descriptionClassSecurity>",
|
||||
body,
|
||||
re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
if match is None:
|
||||
return None
|
||||
return " ".join(match.group(1).split()) or None
|
||||
|
||||
async def companyfacts(self, cik: int | str) -> dict[str, Any]:
|
||||
"""Raw companyfacts JSON ({cik, entityName, facts})."""
|
||||
return await self.get_json(f"{_DATA}/api/xbrl/companyfacts/CIK{cik10(cik)}.json")
|
||||
|
||||
async def latest_index_date(self, today: date | None = None) -> date | None:
|
||||
"""The most recent published daily-index date (drives the revision). Checks
|
||||
the current quarter, falling back to the previous one at a quarter boundary."""
|
||||
today = today or date.today()
|
||||
for year, qtr in _quarters_back(today, 2):
|
||||
url = f"{_WWW}/Archives/edgar/daily-index/{year}/QTR{qtr}/index.json"
|
||||
try:
|
||||
idx = await self.get_json(url)
|
||||
except SecNotFoundError:
|
||||
continue # quarter dir absent — only 404 is "missing"
|
||||
dates = [
|
||||
d
|
||||
for item in idx.get("directory", {}).get("item", [])
|
||||
if (d := _index_file_date(item.get("name", ""))) is not None
|
||||
and d <= today
|
||||
]
|
||||
if dates:
|
||||
return max(dates)
|
||||
return None
|
||||
|
||||
async def daily_index(self, day: date) -> list[dict[str, Any]]:
|
||||
"""Parse the daily form index into 10-K/10-Q(/A) rows for all issuers.
|
||||
|
||||
Returns [{form, cik, accession, company}]. The caller filters to the
|
||||
tracked universe. A missing index (weekend/holiday/not-yet-published)
|
||||
returns [] rather than raising.
|
||||
"""
|
||||
qtr = (day.month - 1) // 3 + 1
|
||||
url = f"{_WWW}/Archives/edgar/daily-index/{day.year}/QTR{qtr}/form.{day:%Y%m%d}.idx"
|
||||
try:
|
||||
text = await self.get_text(url)
|
||||
except SecNotFoundError:
|
||||
# Absent on a weekend is routine (SEC publishes business days only); on a
|
||||
# weekday it is either a market holiday or something worth a look — a SEC
|
||||
# hiccup, or a rejection page misread as absent, would otherwise let the
|
||||
# importer advance past real filings silently. Log-level only, no alert:
|
||||
# cheaper than carrying a holiday calendar just to stay quiet ~10 days/yr.
|
||||
logger.log(
|
||||
logging.INFO if day.weekday() >= 5 else logging.WARNING,
|
||||
"no daily index published for %s (%s)",
|
||||
day,
|
||||
f"{day:%a}",
|
||||
)
|
||||
return [] # weekend/holiday/not-yet-published; other errors propagate
|
||||
return _parse_form_index(text)
|
||||
|
||||
|
||||
def _rows_from_arrays(arrays: dict[str, list]) -> list[dict[str, Any]]:
|
||||
"""Turn SEC's parallel-array filing block into row dicts (keeping only 10-K/10-Q
|
||||
family filings — the ones that carry XBRL fundamentals)."""
|
||||
forms = arrays.get("form", [])
|
||||
out: list[dict[str, Any]] = []
|
||||
for i, form in enumerate(forms):
|
||||
if form not in _FORMS_10:
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"accession": arrays["accessionNumber"][i],
|
||||
"form": form,
|
||||
"report_date": arrays["reportDate"][i] or None,
|
||||
"filing_date": arrays["filingDate"][i] or None,
|
||||
"acceptance_datetime": arrays["acceptanceDateTime"][i] or None,
|
||||
"is_xbrl": bool(arrays.get("isXBRL", [0] * len(forms))[i]),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _parse_form_index(text: str) -> list[dict[str, Any]]:
|
||||
"""Parse a daily ``form.YYYYMMDD.idx`` (fixed columns: Form / Company / CIK /
|
||||
Date Filed / File Name-with-accession)."""
|
||||
rows: list[dict[str, Any]] = []
|
||||
started = False
|
||||
for line in text.splitlines():
|
||||
if not started:
|
||||
if set(line.strip()) == {"-"}: # the dashed separator row
|
||||
started = True
|
||||
continue
|
||||
parts = line.split()
|
||||
if len(parts) < 5:
|
||||
continue
|
||||
form = parts[0]
|
||||
if form not in _FORMS_10:
|
||||
continue
|
||||
path = parts[-1] # edgar/data/<cik>/<accession>.txt
|
||||
cik = _cik_from_path(path)
|
||||
accession = _accession_from_path(path)
|
||||
if cik is None or accession is None:
|
||||
continue
|
||||
rows.append({"form": form, "cik": cik, "accession": accession, "path": path})
|
||||
return rows
|
||||
|
||||
|
||||
def _retry_after_seconds(resp: httpx.Response) -> float | None:
|
||||
"""Parse a numeric-seconds Retry-After header (SEC uses seconds), capped."""
|
||||
raw = resp.headers.get("Retry-After")
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return min(float(raw), 60.0)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _index_file_date(name: str) -> date | None:
|
||||
if name.startswith("form.") and name.endswith(".idx"):
|
||||
try:
|
||||
return datetime.strptime(name[5:13], "%Y%m%d").date()
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _quarters_back(today: date, n: int) -> list[tuple[int, int]]:
|
||||
"""(year, quarter) for `today`'s quarter and the previous n-1, newest first."""
|
||||
q = (today.month - 1) // 3 + 1
|
||||
out = []
|
||||
y = today.year
|
||||
for _ in range(n):
|
||||
out.append((y, q))
|
||||
q -= 1
|
||||
if q == 0:
|
||||
q = 4
|
||||
y -= 1
|
||||
return out
|
||||
|
||||
|
||||
def _cik_from_path(path: str) -> int | None:
|
||||
segs = path.split("/")
|
||||
if len(segs) >= 3 and segs[2].isdigit():
|
||||
return int(segs[2])
|
||||
return None
|
||||
|
||||
|
||||
def _accession_from_path(path: str) -> str | None:
|
||||
stem = path.rsplit("/", 1)[-1]
|
||||
if stem.endswith(".txt"):
|
||||
stem = stem[:-4]
|
||||
return stem or None
|
||||
@@ -0,0 +1,610 @@
|
||||
"""Pure parser: SEC companyfacts -> fundamental_snapshots rows.
|
||||
|
||||
Turns one issuer's `companyfacts` JSON (+ its submissions filing metadata) into
|
||||
per-accession snapshot rows for the filing's **primary period**, following the
|
||||
A3 design (docs/dolt-sec-a3-design.md). No I/O, no DB — unit-testable against a
|
||||
fixture and verifiable against a real companyfacts pull.
|
||||
|
||||
The load-bearing rules (design Decision 2 + review):
|
||||
- Period identity comes from `end == submissions.reportDate`, never `fy/fp`
|
||||
(fy/fp is the *filing's* context; comparatives inside a filing repeat it).
|
||||
This applies to the stored `fiscal_year`/`fiscal_period` too: they are derived
|
||||
from `reportDate` against the issuer's `fiscalYearEnd` (see `_period_identity`),
|
||||
because SEC's fy/fp collide and invert often enough to break the quarter chain.
|
||||
- Duration facts are stored as **cumulative YTD**: pick the fact whose span
|
||||
matches the fiscal-period-to-date length (Q1≈3mo … FY≈12mo) within tolerance.
|
||||
If no YTD-length fact exists, store null — never a discrete masquerading as YTD.
|
||||
- Balance-sheet instants are taken at `end == reportDate`. `shares_outstanding`
|
||||
is a single consolidated value: the cover-page `dei` fact (its own cover-date
|
||||
`end` stored separately) if present, else `us-gaap:CommonStockSharesOutstanding`
|
||||
at period end (e.g. Alphabet has no `dei` fact) — never a class sum or the
|
||||
weighted-average/diluted count. Multi-class issuers report it per class, which
|
||||
is dimensional and therefore absent from companyfacts entirely, so
|
||||
`weighted_avg_diluted_shares` is stored alongside as an explicit fallback for
|
||||
market cap — a separate column, never backfilled into `shares_outstanding`.
|
||||
- Cash and debt composites are aggregate-first and mutually exclusive (each
|
||||
source tag counted at most once).
|
||||
|
||||
`parse_snapshots` separates `skipped_filings` (no usable row produced) from
|
||||
`field_issues` (a row was produced but a field is null/ambiguous) — callers must
|
||||
not treat field issues as missing coverage.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any, NamedTuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Expected YTD span (days) per fiscal period; a duration fact must land within
|
||||
# tolerance of this to count as the period's cumulative value.
|
||||
_EXPECTED_YTD_DAYS = {"Q1": 91, "Q2": 182, "Q3": 273, "FY": 365}
|
||||
# Period identity (see _period_identity): how far a quarter end sits before its
|
||||
# fiscal-year end, and how far a fiscal-year end may drift from the nominal MMDD.
|
||||
# The quarter bands are 91 days apart, so ±35 stays unambiguous even for a 4-4-5
|
||||
# filer whose 16-week Q4 puts Q3 112 days out.
|
||||
_QUARTER_DAYS_TO_FY_END = {"Q1": 273, "Q2": 182, "Q3": 91}
|
||||
_QUARTER_TOLERANCE_DAYS = 35
|
||||
_FYE_DRIFT_TOLERANCE_DAYS = 21
|
||||
# Covers 52/53-week calendars *and* 4-4-5 retail ones (12/12/12/16 weeks), whose
|
||||
# YTD-Q3 is 36 weeks = 251-252 days and missed a 20-day tolerance by ~2 -- so
|
||||
# COST/PEP lost Q3 every year, breaking the quarter chain and nulling TTM + YoY.
|
||||
# Q1 84d, Q2 168d and FY 364d were always inside. Adjacent periods stay
|
||||
# unambiguous at 25 (66-116, 157-207, 248-298, 340-390).
|
||||
_YTD_TOLERANCE_DAYS = 25
|
||||
|
||||
# us-gaap duration concepts (money), priority order; first present wins.
|
||||
_DURATION_USD = {
|
||||
# Order is load-bearing (first present wins) and the tail entries are
|
||||
# deliberately *appended*: every issuer that already resolved keeps the same
|
||||
# concept, and only issuers that resolved to nothing gain a value.
|
||||
# - IncludingAssessedTax: REITs/consumer filers that tag only this variant
|
||||
# (e.g. ARE, KHC) reported no revenue at all.
|
||||
# - RevenuesNetOfInterestExpense: the banks' total-revenue tag. JPM/GS/WFC
|
||||
# tag it in every 10-Q and `Revenues` only (if at all) in the 10-K.
|
||||
"revenue": [
|
||||
"RevenueFromContractWithCustomerExcludingAssessedTax",
|
||||
"Revenues",
|
||||
"SalesRevenueNet",
|
||||
"RevenueFromContractWithCustomerIncludingAssessedTax",
|
||||
"RevenuesNetOfInterestExpense",
|
||||
],
|
||||
"net_income": ["NetIncomeLoss"],
|
||||
"operating_income": ["OperatingIncomeLoss"],
|
||||
"cfo": [
|
||||
"NetCashProvidedByUsedInOperatingActivities",
|
||||
"NetCashProvidedByUsedInOperatingActivitiesContinuingOperations",
|
||||
],
|
||||
"capex": [
|
||||
"PaymentsToAcquirePropertyPlantAndEquipment",
|
||||
"PaymentsToAcquireProductiveAssets",
|
||||
],
|
||||
"depreciation_amortization": [
|
||||
"DepreciationDepletionAndAmortization",
|
||||
"DepreciationAmortizationAndAccretionNet",
|
||||
"DepreciationAndAmortization",
|
||||
],
|
||||
}
|
||||
# unit USD/shares. Appended (not reordered) so any issuer that already resolved
|
||||
# keeps the same concept. REG tags only the continuing-operations variant on every
|
||||
# filing; FCX switches by form type -- EarningsPerShareDiluted in its 10-Qs, the
|
||||
# continuing-ops tag in its 10-K -- which nulled the FY row and killed Q4 + TTM.
|
||||
# The basic variants are a last resort for a period that tags no diluted EPS at
|
||||
# all (PPL's 2026 Q1). Basic ignores option/convert dilution so it slightly
|
||||
# overstates EPS (~1.2% for PPL), but only fires when diluted is entirely absent,
|
||||
# and high-dilution names always tag diluted -- so it never displaces a real one.
|
||||
_EPS_CONCEPTS = [
|
||||
"EarningsPerShareDiluted",
|
||||
"IncomeLossFromContinuingOperationsPerDilutedShare",
|
||||
"EarningsPerShareBasic",
|
||||
"IncomeLossFromContinuingOperationsPerBasicShare",
|
||||
]
|
||||
# Weighted-average diluted share count (unit "shares"), the market-cap fallback
|
||||
# for multi-class issuers whose cover-page count is dimensional and therefore
|
||||
# absent from companyfacts. Always present, since EPS is computed from it.
|
||||
_WEIGHTED_AVG_SHARE_CONCEPTS = [
|
||||
"WeightedAverageNumberOfDilutedSharesOutstanding",
|
||||
"WeightedAverageNumberOfSharesOutstandingBasicAndDiluted",
|
||||
]
|
||||
# us-gaap instant (balance-sheet) concepts, at end == reportDate.
|
||||
_CASH = ["CashAndCashEquivalentsAtCarryingValue"]
|
||||
_ST_INVESTMENTS = ["ShortTermInvestments", "MarketableSecuritiesCurrent"] # pick one
|
||||
# Debt is tagged in four mutually exclusive styles across large filers, and
|
||||
# composing a total means knowing which span each concept covers (measured
|
||||
# 2026-08 over a 20-issuer sample; the counts below are from it).
|
||||
#
|
||||
# ``LongTermDebt`` already spans current + noncurrent maturities — Apple tags all
|
||||
# three and 71.34bn + 11.01bn = 82.30bn confirms it — so its complement is only
|
||||
# genuinely short-term borrowing.
|
||||
_LONG_TERM_DEBT_AGG = ["LongTermDebt"]
|
||||
# Noncurrent-only balance-sheet lines, needing a current complement added.
|
||||
# ``LongTermDebtAndCapitalLeaseObligations`` is what KO, HD, T, XOM and CVX tag
|
||||
# and nothing read it before: AT&T reported no total_debt at all against 134bn
|
||||
# tagged, and Coca-Cola reported 0.25bn of commercial paper against 39bn.
|
||||
_LONG_TERM_DEBT_NONCURRENT = [
|
||||
"LongTermDebtNoncurrent",
|
||||
"LongTermDebtAndCapitalLeaseObligations",
|
||||
]
|
||||
_LONG_TERM_DEBT_CURRENT = ["LongTermDebtCurrent"]
|
||||
# REITs that tag no aggregate at all, carrying a secured and an unsecured side
|
||||
# instead. Both sides are required, because ``NotesPayable`` does not mean the
|
||||
# same thing across issuers (measured 2026-08 over 14 REITs):
|
||||
# - MAA tags NotesPayable 5.66bn = UnsecuredDebt 5.30bn + SecuredDebt 0.36bn
|
||||
# exactly, so there it IS the total and adding SecuredDebt double-counts.
|
||||
# - EQR/VMRK tags NotesPayable alongside a *larger* SecuredDebt (5.38bn vs
|
||||
# 6.38bn in 2013), so there it is only the unsecured component.
|
||||
# ``UnsecuredDebt`` is what separates them: where it is tagged it is the
|
||||
# unambiguous unsecured side and NotesPayable is ignored; where it is absent,
|
||||
# NotesPayable is that side. Requiring both sides is also what keeps this branch
|
||||
# from inventing a total out of a fragment — Boston Properties tags SecuredDebt
|
||||
# 4.28bn and nothing else against ~15bn of real debt, and Regency tags an
|
||||
# UnsecuredDebt of 0.03bn that is a credit-line draw, not its 5bn of notes.
|
||||
_SECURED_DEBT = ["SecuredDebt"]
|
||||
_UNSECURED_DEBT = ["UnsecuredDebt", "NotesPayable"] # first present wins
|
||||
# ``DebtCurrent`` spans short-term borrowing AND current maturities, so it is the
|
||||
# whole current complement where present and must never be added alongside them.
|
||||
_ALL_CURRENT_DEBT = ["DebtCurrent"]
|
||||
_SHORT_TERM_DEBT = ["ShortTermBorrowings", "CommercialPaper"] # pick one
|
||||
|
||||
|
||||
class Fact(NamedTuple):
|
||||
taxonomy: str
|
||||
concept: str
|
||||
unit: str
|
||||
start: date | None # None => instant
|
||||
end: date
|
||||
val: float
|
||||
fy: int | None
|
||||
fp: str | None
|
||||
|
||||
|
||||
@dataclass
|
||||
class SnapshotRow:
|
||||
cik: str
|
||||
accession: str
|
||||
form: str
|
||||
filed_date: date
|
||||
accepted_at: datetime
|
||||
period_end: date
|
||||
fiscal_year: int
|
||||
fiscal_period: str
|
||||
period_start: date | None = None
|
||||
revenue: float | None = None
|
||||
net_income: float | None = None
|
||||
operating_income: float | None = None
|
||||
diluted_eps: float | None = None
|
||||
cfo: float | None = None
|
||||
capex: float | None = None
|
||||
depreciation_amortization: float | None = None
|
||||
cash_and_st_investments: float | None = None
|
||||
total_debt: float | None = None
|
||||
shares_outstanding: float | None = None
|
||||
shares_outstanding_date: date | None = None
|
||||
weighted_avg_diluted_shares: float | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class FilingMeta:
|
||||
report_date: date
|
||||
filing_date: date
|
||||
accepted_at: datetime
|
||||
form: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParseResult:
|
||||
rows: list[SnapshotRow] = field(default_factory=list)
|
||||
# accessions for which NO row was produced (no facts / no usable period).
|
||||
skipped_filings: list[dict[str, str]] = field(default_factory=list)
|
||||
# accessions with a row but a field-level warning (e.g. ambiguous shares).
|
||||
field_issues: list[dict[str, str]] = field(default_factory=list)
|
||||
|
||||
|
||||
def parse_snapshots(
|
||||
companyfacts: dict[str, Any],
|
||||
filings: dict[str, FilingMeta],
|
||||
accessions: set[str],
|
||||
fiscal_year_end: str | None = None,
|
||||
) -> ParseResult:
|
||||
"""Build snapshot rows for ``accessions`` (those with facts + filing meta).
|
||||
|
||||
``fiscal_year_end`` is the issuer's declared ``submissions.fiscalYearEnd``
|
||||
(MMDD) and seeds period identity (see ``_period_identity``), making it
|
||||
independent of SEC's unreliable fy/fp fields. It is only a hint: the issuer's
|
||||
own 10-K period ends override it (see ``resolve_fiscal_year_end``). With
|
||||
neither available, the old fy/fp behaviour is used.
|
||||
|
||||
``skipped_filings`` = no row produced (missing facts/meta or no usable period
|
||||
identity); ``field_issues`` = a row was produced but a field is null/ambiguous.
|
||||
Callers must not use field issues as failed-row coverage.
|
||||
"""
|
||||
cik = f"{int(companyfacts['cik']):010d}"
|
||||
# The declared value is only a hint; the issuer's own 10-Ks are authoritative.
|
||||
fiscal_year_end = resolve_fiscal_year_end(filings, fiscal_year_end)
|
||||
by_accn = _index_by_accession(companyfacts)
|
||||
result = ParseResult()
|
||||
for accn in accessions:
|
||||
meta = filings.get(accn)
|
||||
facts = by_accn.get(accn)
|
||||
if meta is None or not facts:
|
||||
result.skipped_filings.append({"accession": accn, "reason": "no facts or filing metadata"})
|
||||
continue
|
||||
row, note = _parse_one(cik, accn, facts, meta, fiscal_year_end)
|
||||
if row is None:
|
||||
result.skipped_filings.append({"accession": accn, "reason": note or "unparseable"})
|
||||
continue
|
||||
result.rows.append(row)
|
||||
if note:
|
||||
result.field_issues.append({"accession": accn, "reason": note})
|
||||
return result
|
||||
|
||||
|
||||
def companyfacts_accessions(companyfacts: dict[str, Any]) -> set[str]:
|
||||
"""Every accession that appears anywhere in a companyfacts payload — used by
|
||||
the importer's index↔Company-Facts consistency gate."""
|
||||
return set(_index_by_accession(companyfacts).keys())
|
||||
|
||||
|
||||
def _index_by_accession(companyfacts: dict[str, Any]) -> dict[str, list[Fact]]:
|
||||
"""One pass over companyfacts -> {accession: [Fact, ...]}."""
|
||||
out: dict[str, list[Fact]] = {}
|
||||
for taxonomy, concepts in companyfacts.get("facts", {}).items():
|
||||
for concept, body in concepts.items():
|
||||
for unit, facts in body.get("units", {}).items():
|
||||
for f in facts:
|
||||
accn = f.get("accn")
|
||||
end = _d(f.get("end"))
|
||||
val = f.get("val")
|
||||
# Skip malformed facts so they can't be selected accidentally:
|
||||
# every usable fact needs an accession, an end date, and a
|
||||
# finite numeric value.
|
||||
if not accn or end is None or not _finite(val):
|
||||
continue
|
||||
out.setdefault(accn, []).append(
|
||||
Fact(
|
||||
taxonomy=taxonomy,
|
||||
concept=concept,
|
||||
unit=unit,
|
||||
start=_d(f.get("start")),
|
||||
end=end,
|
||||
val=val,
|
||||
fy=f.get("fy"),
|
||||
fp=f.get("fp"),
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _parse_one(
|
||||
cik: str, accn: str, facts: list[Fact], meta: FilingMeta,
|
||||
fiscal_year_end: str | None = None,
|
||||
) -> tuple[SnapshotRow | None, str | None]:
|
||||
"""Returns (row, note). row is None when there's no usable period identity;
|
||||
note is a validation reason (row-skip reason when row is None, else a
|
||||
field-level issue such as ambiguous shares)."""
|
||||
fy, fp = _period_identity(meta, fiscal_year_end)
|
||||
if fy is None or fp is None:
|
||||
# No fiscal calendar, or a period the calendar cannot place (a transition
|
||||
# period). Fall back to the filing's own context: an imperfect label still
|
||||
# beats dropping the filing entirely.
|
||||
fy, fp = _fiscal_context(facts, meta.report_date)
|
||||
if fy is None or fp not in _EXPECTED_YTD_DAYS:
|
||||
return None, "no usable period identity"
|
||||
|
||||
row = SnapshotRow(
|
||||
cik=cik,
|
||||
accession=accn,
|
||||
form=meta.form,
|
||||
filed_date=meta.filing_date,
|
||||
accepted_at=meta.accepted_at,
|
||||
period_end=meta.report_date,
|
||||
fiscal_year=fy,
|
||||
fiscal_period=fp,
|
||||
)
|
||||
|
||||
# duration YTD facts (money) + EPS
|
||||
for field_name, concepts in _DURATION_USD.items():
|
||||
val, start = _select_ytd(facts, concepts, meta.report_date, fp, "USD")
|
||||
setattr(row, field_name, val)
|
||||
if field_name == "revenue" and start is not None:
|
||||
row.period_start = start
|
||||
eps, eps_start = _select_ytd(facts, _EPS_CONCEPTS, meta.report_date, fp, "USD/shares")
|
||||
row.diluted_eps = eps
|
||||
if row.period_start is None and eps_start is not None:
|
||||
row.period_start = eps_start
|
||||
|
||||
# balance-sheet instants at reportDate
|
||||
row.cash_and_st_investments = _compose_cash(facts, meta.report_date)
|
||||
row.total_debt = _compose_debt(facts, meta.report_date)
|
||||
shares, shares_date, ambiguous = _select_shares(facts, meta.report_date)
|
||||
row.shares_outstanding = shares
|
||||
row.shares_outstanding_date = shares_date
|
||||
row.weighted_avg_diluted_shares = _select_weighted_avg_shares(facts, meta.report_date)
|
||||
|
||||
return row, ("ambiguous shares outstanding" if ambiguous else None)
|
||||
|
||||
|
||||
def resolve_fiscal_year_end(
|
||||
filings: dict[str, FilingMeta], declared: str | None
|
||||
) -> str | None:
|
||||
"""The issuer's fiscal-year-end MMDD, preferring its own 10-K period ends.
|
||||
|
||||
``submissions.fiscalYearEnd`` is *not* reliable: Franklin Resources (BEN)
|
||||
declares 1231 while every one of its 10-Ks ends 09-30. Trusting it put BEN's
|
||||
fiscal Q1 (Dec) 0 days from the claimed year end — matching no quarter band —
|
||||
and labelled its fiscal Q2 (Mar) as Q1, colliding two periods on one key and
|
||||
destroying the quarter chain.
|
||||
|
||||
A 10-K's reportDate **is** the fiscal year end by definition, so it wins
|
||||
whenever one is available; the declared value is only a fallback for an issuer
|
||||
with no annual filing in the set. The most recent 10-K is used, so an issuer
|
||||
that changed its year end is measured against its current calendar.
|
||||
"""
|
||||
annual = [m.report_date for m in filings.values() if m.form.startswith("10-K")]
|
||||
if annual:
|
||||
latest = max(annual)
|
||||
return f"{latest.month:02d}{latest.day:02d}"
|
||||
return declared
|
||||
|
||||
|
||||
def _period_identity(
|
||||
meta: FilingMeta, fiscal_year_end: str | None
|
||||
) -> tuple[int | None, str | None]:
|
||||
"""(fiscal_year, fiscal_period) from the period end and the issuer's fiscal
|
||||
calendar — never from the fy/fp fields.
|
||||
|
||||
SEC's fy/fp describe the *filing*, and they are unreliable as period identity:
|
||||
observed in production, a 10-Q labelled ``FY`` (BXP), a year ending 2025-12-31
|
||||
labelled 2024 (FRT, a December filer), a year ending 2025-06-27 labelled 2027
|
||||
(STX), and four different period ends all labelled 2022 Q3 (PPL). Because
|
||||
readers key on (fiscal_year, fiscal_period), colliding labels silently discard
|
||||
a period and inverted ones scramble the quarter chain — nulling TTM and YoY.
|
||||
|
||||
``period_end`` is authoritative, so identity is derived from it: the form
|
||||
decides FY vs quarter, and distance to the fiscal-year end decides which
|
||||
quarter. Labels need not match the issuer's own naming — a filer whose year
|
||||
ends in early January (DPZ) shifts by one — they need to be unique, monotonic
|
||||
and YoY-aligned, which is all the derivation asks of them. Nothing outside the
|
||||
derivation reads these columns.
|
||||
|
||||
Known limitation: ``fiscalYearEnd`` is the issuer's *current* calendar, so a
|
||||
company that has changed its fiscal year end gets its historical periods
|
||||
measured against the new one. The quarter tolerance shunts most of those to
|
||||
the fy/fp fallback, and a same-key collision resolves newest-wins, so the
|
||||
failure mode is a degraded old year rather than a scrambled current one.
|
||||
"""
|
||||
fy = _fiscal_year_of(meta.report_date, fiscal_year_end)
|
||||
if fy is None:
|
||||
return None, None
|
||||
if meta.form.startswith("10-K"):
|
||||
return fy, "FY"
|
||||
nominal_end = _nominal_fy_end(fy, fiscal_year_end)
|
||||
if nominal_end is None:
|
||||
return None, None
|
||||
remaining = (nominal_end - meta.report_date).days
|
||||
best = min(
|
||||
_QUARTER_DAYS_TO_FY_END,
|
||||
key=lambda k: abs(_QUARTER_DAYS_TO_FY_END[k] - remaining),
|
||||
)
|
||||
if abs(_QUARTER_DAYS_TO_FY_END[best] - remaining) > _QUARTER_TOLERANCE_DAYS:
|
||||
return None, None # transition period or odd filing — let the caller fall back
|
||||
return fy, best
|
||||
|
||||
|
||||
def _nominal_fy_end(year: int, fiscal_year_end: str | None) -> date | None:
|
||||
"""The issuer's nominal fiscal-year end in ``year`` from a MMDD string."""
|
||||
if not fiscal_year_end or len(fiscal_year_end) != 4 or not fiscal_year_end.isdigit():
|
||||
return None
|
||||
month, day = int(fiscal_year_end[:2]), int(fiscal_year_end[2:])
|
||||
if not 1 <= month <= 12 or not 1 <= day <= 31:
|
||||
return None
|
||||
while day > 28: # 52/53-week ends land on 0229/0230/0231 in some filings
|
||||
try:
|
||||
return date(year, month, day)
|
||||
except ValueError:
|
||||
day -= 1
|
||||
return date(year, month, day)
|
||||
|
||||
|
||||
def _fiscal_year_of(period_end: date, fiscal_year_end: str | None) -> int | None:
|
||||
"""Which fiscal year ``period_end`` belongs to.
|
||||
|
||||
A 52/53-week calendar's real year end drifts around the nominal MMDD (and can
|
||||
cross the calendar year), so allow drift before rolling into the next year.
|
||||
"""
|
||||
nominal = _nominal_fy_end(period_end.year, fiscal_year_end)
|
||||
if nominal is None:
|
||||
return None
|
||||
return (
|
||||
period_end.year
|
||||
if period_end <= nominal + timedelta(days=_FYE_DRIFT_TOLERANCE_DAYS)
|
||||
else period_end.year + 1
|
||||
)
|
||||
|
||||
|
||||
def _fiscal_context(facts: list[Fact], report_date: date) -> tuple[int | None, str | None]:
|
||||
"""The filing's (fy, fp) taken as the majority context among the facts that
|
||||
end at reportDate (the current-period facts, which share the filing's
|
||||
context). Reject a tie so a conflicting context is never chosen arbitrarily."""
|
||||
counts: dict[tuple[int, str], int] = {}
|
||||
for f in facts:
|
||||
if f.end == report_date and f.fy is not None and f.fp:
|
||||
counts[(f.fy, f.fp)] = counts.get((f.fy, f.fp), 0) + 1
|
||||
if not counts:
|
||||
return None, None
|
||||
ranked = sorted(counts.items(), key=lambda kv: kv[1], reverse=True)
|
||||
if len(ranked) > 1 and ranked[0][1] == ranked[1][1]:
|
||||
return None, None # tie → conflicting contexts, reject
|
||||
return ranked[0][0]
|
||||
|
||||
|
||||
def _select_ytd(
|
||||
facts: list[Fact], concepts: list[str], report_date: date, fp: str, unit: str
|
||||
) -> tuple[float | None, date | None]:
|
||||
"""First present concept whose duration fact ends at reportDate and whose span
|
||||
matches the fiscal-period-to-date length. Returns (val, period_start)."""
|
||||
expected = _EXPECTED_YTD_DAYS[fp]
|
||||
for concept in concepts:
|
||||
best: Fact | None = None
|
||||
best_diff: int | None = None
|
||||
for f in facts:
|
||||
if (
|
||||
f.taxonomy != "us-gaap"
|
||||
or f.concept != concept
|
||||
or f.unit != unit
|
||||
or f.start is None
|
||||
or f.end != report_date
|
||||
):
|
||||
continue
|
||||
diff = abs((f.end - f.start).days - expected)
|
||||
if diff <= _YTD_TOLERANCE_DAYS and (best_diff is None or diff < best_diff):
|
||||
best, best_diff = f, diff
|
||||
if best is not None:
|
||||
return float(best.val), best.start
|
||||
return None, None
|
||||
|
||||
|
||||
def _select_instant(facts: list[Fact], concepts: list[str], report_date: date) -> float | None:
|
||||
"""First present instant (balance-sheet) fact at end == reportDate, unit USD."""
|
||||
for concept in concepts:
|
||||
for f in facts:
|
||||
if (
|
||||
f.taxonomy == "us-gaap"
|
||||
and f.concept == concept
|
||||
and f.unit == "USD"
|
||||
and f.start is None
|
||||
and f.end == report_date
|
||||
):
|
||||
return float(f.val)
|
||||
return None
|
||||
|
||||
|
||||
def _compose_cash(facts: list[Fact], report_date: date) -> float | None:
|
||||
cash = _select_instant(facts, _CASH, report_date)
|
||||
st = _select_instant(facts, _ST_INVESTMENTS, report_date) # first present of the two
|
||||
if cash is None and st is None:
|
||||
return None
|
||||
return (cash or 0.0) + (st or 0.0)
|
||||
|
||||
|
||||
def _compose_debt(facts: list[Fact], report_date: date) -> float | None:
|
||||
"""Total debt at ``report_date``, or None when no long-term component is found.
|
||||
|
||||
**A short-term component alone is never a total.** Chevron tags its full debt
|
||||
only in the 10-K, so its 10-Q carries ``ShortTermBorrowings`` of 0.40bn and
|
||||
nothing else; returning that as total debt reads as a near-unlevered issuer
|
||||
carrying 50bn. Since ``_net_debt`` needs both sides and yields nothing when
|
||||
either is missing, None costs a leverage read while the partial value
|
||||
produces a confidently wrong one.
|
||||
"""
|
||||
# An aggregate spanning current + noncurrent: only true short-term is missing.
|
||||
total = _select_instant(facts, _LONG_TERM_DEBT_AGG, report_date)
|
||||
if total is not None:
|
||||
return total + (_select_instant(facts, _SHORT_TERM_DEBT, report_date) or 0.0)
|
||||
|
||||
noncurrent = _select_instant(facts, _LONG_TERM_DEBT_NONCURRENT, report_date)
|
||||
if noncurrent is None:
|
||||
secured = _select_instant(facts, _SECURED_DEBT, report_date)
|
||||
unsecured = _select_instant(facts, _UNSECURED_DEBT, report_date)
|
||||
if secured is None or unsecured is None:
|
||||
return None # one side of a REIT's debt is not its total
|
||||
noncurrent = secured + unsecured
|
||||
|
||||
current = _select_instant(facts, _ALL_CURRENT_DEBT, report_date)
|
||||
if current is None:
|
||||
current = (
|
||||
(_select_instant(facts, _LONG_TERM_DEBT_CURRENT, report_date) or 0.0)
|
||||
+ (_select_instant(facts, _SHORT_TERM_DEBT, report_date) or 0.0)
|
||||
)
|
||||
return noncurrent + current
|
||||
|
||||
|
||||
def _select_shares(
|
||||
facts: list[Fact], report_date: date
|
||||
) -> tuple[float | None, date | None, bool]:
|
||||
"""Issuer-wide shares outstanding as a single consolidated value (never a
|
||||
class sum — companyfacts is non-dimensional — and never weighted-average/
|
||||
diluted). Returns (value, shares_date, ambiguous).
|
||||
|
||||
1. Prefer the `dei:EntityCommonStockSharesOutstanding` cover-page instant;
|
||||
its own end is the shares date (cover date != period_end).
|
||||
2. Else fall back to `us-gaap:CommonStockSharesOutstanding` at period end
|
||||
(e.g. Alphabet has no dei fact); shares date = reportDate.
|
||||
Conflicting values within the chosen source → (None, None, True) to be
|
||||
counted in validation.
|
||||
"""
|
||||
dei = [
|
||||
f
|
||||
for f in facts
|
||||
if f.taxonomy == "dei"
|
||||
and f.concept == "EntityCommonStockSharesOutstanding"
|
||||
and f.unit == "shares"
|
||||
and f.start is None
|
||||
]
|
||||
if dei:
|
||||
if len({f.val for f in dei}) > 1:
|
||||
return None, None, True
|
||||
best = max(dei, key=lambda f: f.end)
|
||||
return float(best.val), best.end, False
|
||||
|
||||
gaap = [
|
||||
f
|
||||
for f in facts
|
||||
if f.taxonomy == "us-gaap"
|
||||
and f.concept == "CommonStockSharesOutstanding"
|
||||
and f.unit == "shares"
|
||||
and f.start is None
|
||||
and f.end == report_date
|
||||
]
|
||||
if gaap:
|
||||
if len({f.val for f in gaap}) > 1:
|
||||
return None, None, True
|
||||
return float(gaap[0].val), report_date, False
|
||||
|
||||
return None, None, False # simply absent — not a conflict
|
||||
|
||||
|
||||
def _select_weighted_avg_shares(facts: list[Fact], report_date: date) -> float | None:
|
||||
"""The most recent quarter's weighted-average diluted share count.
|
||||
|
||||
Deliberately the **shortest** duration ending at reportDate, not the YTD one:
|
||||
the shorter the window the closer the average sits to the current count, which
|
||||
is what a market cap wants. Measured against issuers where the true
|
||||
point-in-time count is available, the quarter average is within ~0.6%.
|
||||
"""
|
||||
best: tuple[int, float] | None = None
|
||||
for concept in _WEIGHTED_AVG_SHARE_CONCEPTS:
|
||||
for f in facts:
|
||||
if (
|
||||
f.taxonomy != "us-gaap"
|
||||
or f.concept != concept
|
||||
or f.unit != "shares"
|
||||
or f.start is None
|
||||
or f.end != report_date
|
||||
or f.val <= 0
|
||||
):
|
||||
continue
|
||||
span = (f.end - f.start).days
|
||||
if best is None or span < best[0]:
|
||||
best = (span, float(f.val))
|
||||
if best is not None:
|
||||
return best[1] # first present concept wins, as elsewhere
|
||||
return None
|
||||
|
||||
|
||||
def _d(value: Any) -> date | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(str(value)[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _finite(value: Any) -> bool:
|
||||
"""True for a finite numeric value (rejects None, bool, strings, NaN/inf)."""
|
||||
return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,163 @@
|
||||
"""Tracked-universe CIK/SIC resolution and the SEC importer's composite revision.
|
||||
|
||||
Resolves the app's tracked tickers to SEC issuers (CIK) and prepares
|
||||
``tickers.cik/sic/sic_description`` back-fills. Also builds the **universe
|
||||
fingerprint** in the importer's composite revision, so adding a ticker changes
|
||||
the revision and forces a run instead of being ``no_op``'d away or starved
|
||||
waiting for its issuer to file (A3 design, Decision 1 review fix).
|
||||
|
||||
**Transaction contract:** resolution is read-only — `resolve_ciks` and
|
||||
`fetch_sic_updates` compute *proposed* updates and mutate nothing. They run in
|
||||
the importer's `stage` (which must not write, or a failed validation would leak
|
||||
changes on the framework's failure commit). The proposals are applied only in
|
||||
`promote`, via `apply_ticker_updates`, atomically with the snapshot inserts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Iterable
|
||||
|
||||
from sqlalchemy import select, update
|
||||
|
||||
from app.models.ticker import Ticker
|
||||
from app.services import settings_store, ticker_service
|
||||
from app.services.earnings_alignment import normalise_symbol
|
||||
from app.services.sec_client import SecClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# JSON {symbol: cik} pinning a ticker to a specific registrant, overriding
|
||||
# company_tickers.json. Needed when SEC maps a ticker to a successor entity that
|
||||
# has not filed: XOM points at CIK 2115436 "ExxonMobil Holdings Corp" (zero XBRL
|
||||
# filings) while every 10-K/10-Q — including one filed 2026-05-04 — is still under
|
||||
# CIK 34088. Which registrant is the real filer is a judgement about a corporate
|
||||
# event, so it is pinned explicitly rather than guessed. The importer's
|
||||
# `no_xbrl_filings` warning is what tells you a pin is needed.
|
||||
CIK_OVERRIDES_KEY = "sec_cik_overrides"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ResolvedUniverse:
|
||||
"""Read-only result of CIK resolution. `cik_updates` are proposed writes
|
||||
(ticker_id → new cik string) applied later in promote."""
|
||||
|
||||
symbol_to_cik: dict[str, int] = field(default_factory=dict)
|
||||
cik_to_ticker_ids: dict[int, list[int]] = field(default_factory=dict)
|
||||
cik_updates: list[tuple[int, str]] = field(default_factory=list)
|
||||
|
||||
|
||||
async def resolve_ciks(db, client: SecClient) -> ResolvedUniverse:
|
||||
"""Resolve tracked tickers to CIKs via company_tickers.json. **Read-only** —
|
||||
returns the mapping + proposed `tickers.cik` writes; mutates nothing."""
|
||||
ticker_to_cik = await client.company_tickers()
|
||||
overrides = await cik_overrides(db)
|
||||
rows = (
|
||||
await db.execute(
|
||||
ticker_service.active_only(select(Ticker.id, Ticker.symbol, Ticker.cik))
|
||||
)
|
||||
).all()
|
||||
|
||||
result = ResolvedUniverse()
|
||||
for tid, symbol, current_cik in rows:
|
||||
if not symbol:
|
||||
continue
|
||||
sym = normalise_symbol(symbol)
|
||||
cik = overrides.get(sym) or ticker_to_cik.get(sym)
|
||||
if cik is None:
|
||||
continue # ADRs / non-SEC issuers — snapshots simply absent
|
||||
result.symbol_to_cik[sym] = cik
|
||||
result.cik_to_ticker_ids.setdefault(cik, []).append(tid)
|
||||
if current_cik != f"{cik:010d}":
|
||||
result.cik_updates.append((tid, f"{cik:010d}"))
|
||||
logger.info(
|
||||
"resolve_ciks: %d resolved, %d proposed cik updates",
|
||||
len(result.symbol_to_cik),
|
||||
len(result.cik_updates),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
async def cik_overrides(db) -> dict[str, int]:
|
||||
"""Manual ``{symbol: cik}`` pins from ``SystemSetting[CIK_OVERRIDES_KEY]``.
|
||||
|
||||
A malformed setting must never take the importer down, so anything unparseable
|
||||
is logged and ignored — the run then falls back to company_tickers.json.
|
||||
"""
|
||||
raw = await settings_store.get_value(db, CIK_OVERRIDES_KEY)
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
loaded = json.loads(raw)
|
||||
except (TypeError, ValueError):
|
||||
logger.warning("%s is not valid JSON — ignoring CIK overrides", CIK_OVERRIDES_KEY)
|
||||
return {}
|
||||
if not isinstance(loaded, dict):
|
||||
logger.warning("%s must be a {symbol: cik} object — ignoring", CIK_OVERRIDES_KEY)
|
||||
return {}
|
||||
out: dict[str, int] = {}
|
||||
for symbol, cik in loaded.items():
|
||||
try:
|
||||
out[normalise_symbol(str(symbol))] = int(cik)
|
||||
except (TypeError, ValueError):
|
||||
logger.warning("%s: bad entry %r -> %r — ignoring", CIK_OVERRIDES_KEY, symbol, cik)
|
||||
if out:
|
||||
logger.info("resolve_ciks: %d CIK override(s) applied: %s", len(out), sorted(out))
|
||||
return out
|
||||
|
||||
|
||||
async def fetch_sic_updates(
|
||||
client: SecClient, cik_to_ticker_ids: dict[int, Iterable[int]]
|
||||
) -> list[tuple[int, str | None, str | None]]:
|
||||
"""Fetch SIC for each CIK (recent-only submissions, no history shards) and
|
||||
return proposed `(ticker_id, sic, sic_description)` writes. **Read-only** — no
|
||||
DB mutation. Callers pass only the CIKs that need it (e.g. missing a SIC)."""
|
||||
updates: list[tuple[int, str | None, str | None]] = []
|
||||
for cik, ticker_ids in cik_to_ticker_ids.items():
|
||||
sub = await client.submissions(cik, include_history=False)
|
||||
sic = str(sub["sic"]) if sub.get("sic") else None
|
||||
desc = sub.get("sic_description")
|
||||
for tid in ticker_ids:
|
||||
updates.append((tid, sic, desc))
|
||||
return updates
|
||||
|
||||
|
||||
async def apply_ticker_updates(
|
||||
db,
|
||||
resolved: ResolvedUniverse,
|
||||
sic_updates: list[tuple[int, str | None, str | None]] | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""Apply the proposed cik / sic writes. **The only writer** — call inside
|
||||
promote so it commits atomically with the snapshot inserts."""
|
||||
for tid, cik in resolved.cik_updates:
|
||||
await db.execute(update(Ticker).where(Ticker.id == tid).values(cik=cik))
|
||||
for tid, sic, desc in sic_updates or []:
|
||||
await db.execute(
|
||||
update(Ticker).where(Ticker.id == tid).values(sic=sic, sic_description=desc)
|
||||
)
|
||||
return {"cik_updates": len(resolved.cik_updates), "sic_updates": len(sic_updates or [])}
|
||||
|
||||
|
||||
def universe_fingerprint(symbol_to_cik: dict[str, int]) -> str:
|
||||
"""Stable short hash of the tracked symbol->CIK set. Changes whenever a ticker
|
||||
is added/removed or its CIK mapping changes."""
|
||||
canonical = ";".join(f"{sym}:{cik}" for sym, cik in sorted(symbol_to_cik.items()))
|
||||
return hashlib.blake2b(canonical.encode("utf-8"), digest_size=12).hexdigest()
|
||||
|
||||
|
||||
def index_content_hash(index_rows: Iterable[dict]) -> str:
|
||||
"""Order-independent hash of the tracked index accessions consumed this run."""
|
||||
keys = sorted(f"{r['cik']}/{r['accession']}" for r in index_rows)
|
||||
return hashlib.blake2b("|".join(keys).encode("utf-8"), digest_size=12).hexdigest()
|
||||
|
||||
|
||||
def compose_revision(index_date, content_hash: str, symbol_to_cik: dict[str, int]) -> str:
|
||||
"""Composite revision = processed index date + index-content hash + universe
|
||||
fingerprint. Equal across runs ⇒ nothing new ⇒ no_op. Rejects a missing index
|
||||
date rather than emitting a `None:...` revision that could false-match."""
|
||||
if index_date is None:
|
||||
raise ValueError("compose_revision requires a non-null index date")
|
||||
return f"{index_date}:{content_hash}:{universe_fingerprint(symbol_to_cik)}"
|
||||
@@ -0,0 +1,365 @@
|
||||
"""Shadow book — the validated strategy, traded automatically.
|
||||
|
||||
The discretionary paper book only ever contains trades the user chose to take,
|
||||
inside a ~20 minute window, on days they were available. The backtest that
|
||||
validated this strategy does none of that: it takes the top-ranked qualified
|
||||
setups up to capacity, every session, with no human involved. That difference
|
||||
makes the manual book unusable as out-of-sample evidence — it measures the
|
||||
strategy *plus* discretion and availability.
|
||||
|
||||
The shadow book closes that gap. It mirrors ``_simulate_portfolio``'s selection
|
||||
rule exactly and shares the manual book's exit policy, so the only difference
|
||||
between the two books is *which* qualified setups get taken.
|
||||
|
||||
Parity is the load-bearing property here. Selection ordering comes from the
|
||||
stored ``strategy_rank`` the scanner already wrote (the same 80/20
|
||||
momentum/vol blend the backtest ranks on) rather than being recomputed, so the
|
||||
two cannot drift apart.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.paper_trade import PaperTrade
|
||||
from app.models.ticker import Ticker
|
||||
from app.models.trade_setup import TradeSetup
|
||||
from app.models.user import User
|
||||
from app.services import settings_store
|
||||
from app.services.qualification import setup_qualifies
|
||||
from app.services.trade_policy import SHADOW_BOOK, get_reentry_gate_locks
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
KEY_ENABLED = "shadow_book_enabled"
|
||||
KEY_CAPACITY = "shadow_book_capacity"
|
||||
KEY_RISK_PCT = "shadow_book_risk_pct"
|
||||
KEY_START_EQUITY = "shadow_book_start_equity"
|
||||
|
||||
# Matches the validated configuration: 1% fixed-fractional risk, and a count cap
|
||||
# set as headroom rather than a target — see backtest_service.SIM_MAX_POSITIONS,
|
||||
# which this must track. NOTIONAL_CAP below saturates the book near 12 positions,
|
||||
# so the count cap should simply never bind. Start equity is only a sizing base —
|
||||
# comparisons are drawn in percent and R-multiples, never in raw currency.
|
||||
DEFAULT_CAPACITY = 15
|
||||
DEFAULT_RISK_PCT = 1.0
|
||||
DEFAULT_START_EQUITY = 100_000.0
|
||||
|
||||
# Mirrors ``_simulate_portfolio``'s SIM_NOTIONAL_CAP: no single position may
|
||||
# exceed this fraction of equity, and the book never uses margin. Without the
|
||||
# cap, a setup with a tight stop turns 1% risk into a position several times
|
||||
# equity — a leveraged trade the validated strategy would never have taken.
|
||||
NOTIONAL_CAP = 0.20
|
||||
|
||||
# If the last successful scan completed longer ago than this, no scan ran in the
|
||||
# current pipeline pass (scans are daily, ~24h apart), so there is nothing fresh
|
||||
# to trade. Comfortably longer than a scan's own duration, far shorter than the
|
||||
# gap between scans.
|
||||
MAX_SCAN_AGE = timedelta(hours=6)
|
||||
|
||||
|
||||
async def get_config(db: AsyncSession) -> dict:
|
||||
"""Shadow book sizing/capacity config, falling back to validated defaults."""
|
||||
raw = await settings_store.get_map(
|
||||
db, [KEY_CAPACITY, KEY_RISK_PCT, KEY_START_EQUITY]
|
||||
)
|
||||
|
||||
def _num(key: str, default: float, *, minimum: float, maximum: float) -> float:
|
||||
try:
|
||||
value = float(raw.get(key) or default)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return max(minimum, min(maximum, value))
|
||||
|
||||
return {
|
||||
"capacity": int(_num(KEY_CAPACITY, DEFAULT_CAPACITY, minimum=1, maximum=100)),
|
||||
"risk_pct": _num(KEY_RISK_PCT, DEFAULT_RISK_PCT, minimum=0.05, maximum=10.0),
|
||||
"start_equity": _num(
|
||||
KEY_START_EQUITY, DEFAULT_START_EQUITY, minimum=1000.0, maximum=1e9
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
async def is_enabled(db: AsyncSession) -> bool:
|
||||
"""Shadow book writes trades to the live book, so it is opt-in."""
|
||||
value = await settings_store.get_value(db, KEY_ENABLED, "false")
|
||||
return str(value).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
async def equity_and_cash(
|
||||
db: AsyncSession, start_equity: float, positions: list[PaperTrade]
|
||||
) -> tuple[float, float]:
|
||||
"""Marked equity and free cash, matching ``_simulate_portfolio``.
|
||||
|
||||
The simulator sizes from *marked* equity — cash plus open positions at their
|
||||
latest close — and spends from cash, so a book that is fully invested cannot
|
||||
keep buying. Sizing from realized P&L alone would drift away from the
|
||||
backtest as soon as positions were held across a scan.
|
||||
"""
|
||||
from app.services.paper_trade_service import _latest_closes
|
||||
|
||||
result = await db.execute(
|
||||
select(PaperTrade).where(
|
||||
PaperTrade.book == SHADOW_BOOK,
|
||||
PaperTrade.status == "closed",
|
||||
PaperTrade.close_price.is_not(None),
|
||||
)
|
||||
)
|
||||
realized = 0.0
|
||||
for trade in result.scalars():
|
||||
per_share = (
|
||||
trade.close_price - trade.entry_price
|
||||
if trade.direction == "long"
|
||||
else trade.entry_price - trade.close_price
|
||||
)
|
||||
realized += per_share * trade.shares
|
||||
|
||||
open_cost = sum(p.entry_price * p.shares for p in positions)
|
||||
marks = await _latest_closes(db, {p.ticker_id for p in positions})
|
||||
open_value = sum(
|
||||
(marks.get(p.ticker_id) or p.entry_price) * p.shares for p in positions
|
||||
)
|
||||
|
||||
cash = start_equity + realized - open_cost
|
||||
return cash + open_value, cash
|
||||
|
||||
|
||||
def position_shares(
|
||||
equity: float,
|
||||
risk_pct: float,
|
||||
entry: float,
|
||||
stop: float,
|
||||
*,
|
||||
cash_available: float | None = None,
|
||||
) -> float:
|
||||
"""Shares to buy, sized exactly as ``_simulate_portfolio`` sizes them.
|
||||
|
||||
Fixed-fractional risk first, then the two caps the simulator applies: no
|
||||
position may exceed ``NOTIONAL_CAP`` of equity, and the book cannot spend
|
||||
cash it does not have. Dropping either cap lets a tight stop produce a
|
||||
leveraged position and breaks compounding parity with the backtest.
|
||||
"""
|
||||
risk_per_share = abs(entry - stop)
|
||||
if risk_per_share <= 0 or equity <= 0 or entry <= 0:
|
||||
return 0.0
|
||||
|
||||
shares = (equity * risk_pct / 100.0) / risk_per_share
|
||||
shares = min(shares, (equity * NOTIONAL_CAP) / entry)
|
||||
if cash_available is not None:
|
||||
shares = min(shares, max(0.0, cash_available) / entry)
|
||||
# Dust guard, as in the simulator: sub-$1 positions are noise, not trades.
|
||||
return shares if shares * entry >= 1.0 else 0.0
|
||||
|
||||
|
||||
async def _open_positions(db: AsyncSession) -> list[PaperTrade]:
|
||||
result = await db.execute(
|
||||
select(PaperTrade).where(
|
||||
PaperTrade.book == SHADOW_BOOK, PaperTrade.status == "open"
|
||||
)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def _shadow_user_id(db: AsyncSession) -> int | None:
|
||||
"""Shadow trades are not owned by a person; attach them to the first user."""
|
||||
result = await db.execute(select(User.id).order_by(User.id.asc()).limit(1))
|
||||
row = result.first()
|
||||
return int(row[0]) if row else None
|
||||
|
||||
|
||||
async def _scan_run_to_trade(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
now: datetime,
|
||||
expected_run_id: str | None = None,
|
||||
) -> str | None:
|
||||
"""The run id whose setups the shadow book may act on, or None.
|
||||
|
||||
* ``expected_run_id`` set (pipeline step): the stored run id must match it
|
||||
exactly. This is the airtight guarantee — a scan that was disabled or
|
||||
failed in *this* pipeline never stamped this id, and a concurrent manual
|
||||
scan (a separate APScheduler job, not serialised against the pipeline)
|
||||
stamps its own id even when it finishes last, so neither can be mistaken
|
||||
for the pipeline's own scan. Timestamp order alone cannot tell them apart.
|
||||
* ``expected_run_id`` None (direct Admin trigger): fall back to the freshness
|
||||
window on the last scan's own id. There is no pipeline scan to bind to, so
|
||||
acting on a recent scan is the operator's explicit choice.
|
||||
|
||||
Setups are then selected by ``scan_run_id`` equal to the returned id, so a
|
||||
concurrent scan's rows in the same time window are excluded by identity.
|
||||
"""
|
||||
from app.services import rr_scanner_service as rr
|
||||
|
||||
completed = _parse_dt(
|
||||
await settings_store.get_value(db, rr.KEY_LAST_SCAN_COMPLETED)
|
||||
)
|
||||
run_id = await settings_store.get_value(db, rr.KEY_LAST_SCAN_RUN_ID)
|
||||
if completed is None or not run_id:
|
||||
return None
|
||||
if expected_run_id is not None:
|
||||
return run_id if run_id == expected_run_id else None
|
||||
if now - completed > MAX_SCAN_AGE:
|
||||
return None
|
||||
return run_id
|
||||
|
||||
|
||||
def _parse_dt(raw: str | None) -> datetime | None:
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
async def _todays_qualified_setups(
|
||||
db: AsyncSession,
|
||||
config: dict,
|
||||
*,
|
||||
now: datetime,
|
||||
expected_run_id: str | None = None,
|
||||
) -> list[TradeSetup]:
|
||||
"""Long-only qualified setups from the scan we may act on, best rank first.
|
||||
|
||||
Order matters here, and matches the review's requirement:
|
||||
|
||||
1. Take only rows the matched scan produced (``scan_run_id == run id``). A
|
||||
previous run, or a manual scan overlapping in time, carries a different
|
||||
id and is excluded by identity — not by a time window it could write into.
|
||||
2. Keep long only. The validated strategy is long-only, but the gate permits
|
||||
shorts when ``min_momentum_percentile`` is 0 (a legal admin setting), and
|
||||
the cash accounting assumes longs — so this is enforced here, not left to
|
||||
the gate.
|
||||
3. Deduplicate to the latest row per ticker *before* qualifying, so a newer
|
||||
unqualified row correctly suppresses an older qualified one rather than
|
||||
the reverse.
|
||||
4. Qualify, then rank by ``strategy_rank`` (unranked sort last).
|
||||
"""
|
||||
run_id = await _scan_run_to_trade(db, now=now, expected_run_id=expected_run_id)
|
||||
if run_id is None:
|
||||
return []
|
||||
|
||||
result = await db.execute(
|
||||
select(TradeSetup).where(TradeSetup.scan_run_id == run_id)
|
||||
)
|
||||
rows = [s for s in result.scalars() if (s.direction or "long") == "long"]
|
||||
|
||||
latest: dict[int, TradeSetup] = {}
|
||||
for setup in rows:
|
||||
held = latest.get(setup.ticker_id)
|
||||
if held is None or (setup.detected_at, setup.id) > (
|
||||
held.detected_at,
|
||||
held.id,
|
||||
):
|
||||
latest[setup.ticker_id] = setup
|
||||
|
||||
qualified = [s for s in latest.values() if setup_qualifies(s, config)]
|
||||
return sorted(
|
||||
qualified,
|
||||
key=lambda s: (
|
||||
s.strategy_rank if s.strategy_rank is not None else float("-inf")
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
|
||||
async def open_shadow_positions(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
activation_config: dict,
|
||||
opened_at: datetime | None = None,
|
||||
expected_run_id: str | None = None,
|
||||
) -> dict:
|
||||
"""Fill free capacity with the top-ranked qualified setups.
|
||||
|
||||
Mirrors the backtest: rank the qualified cross-section, walk it top-down,
|
||||
skip anything already held or locked out by post-stop gate-reset, and stop
|
||||
at capacity. Returns a summary for the job log.
|
||||
|
||||
``expected_run_id`` binds this run to the scan that stamped that exact id
|
||||
(the pipeline's own scan), so a scan that failed in this pipeline — or a
|
||||
concurrent manual scan that finished last — cannot substitute for it. See
|
||||
``_scan_run_to_trade``.
|
||||
"""
|
||||
summary = {
|
||||
"opened": 0,
|
||||
"skipped_held": 0,
|
||||
"skipped_locked": 0,
|
||||
"skipped_no_cash": 0,
|
||||
"symbols": [],
|
||||
}
|
||||
config = await get_config(db)
|
||||
|
||||
positions = await _open_positions(db)
|
||||
held = {p.ticker_id for p in positions}
|
||||
free_slots = config["capacity"] - len(positions)
|
||||
if free_slots <= 0:
|
||||
return summary
|
||||
|
||||
user_id = await _shadow_user_id(db)
|
||||
if user_id is None:
|
||||
logger.warning("shadow book skipped: no user to attach trades to")
|
||||
return summary
|
||||
|
||||
locks = await get_reentry_gate_locks(db, book=SHADOW_BOOK)
|
||||
equity, cash = await equity_and_cash(db, config["start_equity"], positions)
|
||||
timestamp = opened_at or datetime.now(timezone.utc)
|
||||
|
||||
candidates = await _todays_qualified_setups(
|
||||
db, activation_config, now=timestamp, expected_run_id=expected_run_id
|
||||
)
|
||||
for setup in candidates:
|
||||
if free_slots <= 0:
|
||||
break
|
||||
if setup.ticker_id in held:
|
||||
summary["skipped_held"] += 1
|
||||
continue
|
||||
if setup.ticker_id in locks:
|
||||
summary["skipped_locked"] += 1
|
||||
continue
|
||||
|
||||
entry = float(setup.entry_price or 0.0)
|
||||
stop = float(setup.stop_loss or 0.0)
|
||||
shares = position_shares(
|
||||
equity, config["risk_pct"], entry, stop, cash_available=cash
|
||||
)
|
||||
if shares <= 0:
|
||||
summary["skipped_no_cash"] += 1
|
||||
continue
|
||||
cash -= shares * entry
|
||||
|
||||
db.add(
|
||||
PaperTrade(
|
||||
user_id=user_id,
|
||||
ticker_id=setup.ticker_id,
|
||||
direction=setup.direction,
|
||||
entry_price=entry,
|
||||
shares=shares,
|
||||
stop_loss=stop,
|
||||
target=float(setup.target or 0.0),
|
||||
status="open",
|
||||
opened_at=timestamp,
|
||||
fill_mode="near_close",
|
||||
book=SHADOW_BOOK,
|
||||
)
|
||||
)
|
||||
held.add(setup.ticker_id)
|
||||
free_slots -= 1
|
||||
summary["opened"] += 1
|
||||
summary["symbols"].append(setup.ticker_id)
|
||||
|
||||
if summary["opened"]:
|
||||
await db.commit()
|
||||
return summary
|
||||
|
||||
|
||||
async def symbols_for(db: AsyncSession, ticker_ids: list[int]) -> list[str]:
|
||||
"""Resolve ticker ids to symbols for logging."""
|
||||
if not ticker_ids:
|
||||
return []
|
||||
result = await db.execute(select(Ticker.symbol).where(Ticker.id.in_(ticker_ids)))
|
||||
return [row[0] for row in result.all()]
|
||||
+586
-77
@@ -1,12 +1,15 @@
|
||||
"""S/R Detector service.
|
||||
|
||||
Detects support/resistance levels from Volume Profile (HVN/LVN) and
|
||||
Pivot Points (swing highs/lows), assigns strength scores, merges nearby
|
||||
levels, tags as support/resistance, and persists to DB.
|
||||
Detects support/resistance levels from Volume Profile (POC/VA/HVN peaks)
|
||||
and Pivot Points (prominent swing highs/lows), plus light psychological
|
||||
round numbers. Scores by rejection-weighted recent touches, merges nearby
|
||||
levels with ATR-adaptive tolerance, tags support/resistance, caps count,
|
||||
and persists to DB.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import delete, select
|
||||
@@ -17,12 +20,43 @@ from app.models.sr_level import SRLevel
|
||||
from app.models.ticker import Ticker
|
||||
from app.services.indicator_service import (
|
||||
_extract_ohlcv,
|
||||
compute_atr,
|
||||
compute_pivot_points,
|
||||
compute_volume_profile,
|
||||
)
|
||||
from app.services.price_service import query_ohlcv
|
||||
|
||||
DEFAULT_TOLERANCE = 0.005 # 0.5%
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tunable constants (keep detection pure / deterministic)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
DEFAULT_TOLERANCE = 0.005 # fallback when ATR unavailable; also API legacy default
|
||||
|
||||
VP_LOOKBACK = 252
|
||||
TOUCH_LOOKBACK = 252
|
||||
PIVOT_LOOKBACK = 504
|
||||
PIVOT_PROMINENCE_ATR = 0.75
|
||||
PIVOT_PROMINENCE_PCT = 0.006
|
||||
|
||||
MERGE_TOL_ATR_MULT = 0.35
|
||||
MERGE_TOL_MIN = 0.004 # 0.4%
|
||||
MERGE_TOL_MAX = 0.015 # 1.5%
|
||||
|
||||
MAX_LEVELS = 16
|
||||
STRENGTH_HALF_LIFE = 60 # bars
|
||||
# Raw respect score is soft-mapped to 0–100 (see _raw_to_strength).
|
||||
STRENGTH_SCALE = 8.0
|
||||
STRENGTH_SOFT_K = 35.0 # higher → slower approach to 100
|
||||
|
||||
ROUND_NUMBER_RANGE = 0.15 # ±15% of spot
|
||||
ROUND_NUMBER_MAX = 8
|
||||
|
||||
# Base strength seed before touch scoring (method priors)
|
||||
_METHOD_BASE_STRENGTH = {
|
||||
"volume_profile": 12,
|
||||
"pivot_point": 8,
|
||||
"round_number": 4,
|
||||
}
|
||||
|
||||
|
||||
async def _get_ticker(db: AsyncSession, symbol: str) -> Ticker:
|
||||
@@ -35,36 +69,235 @@ async def _get_ticker(db: AsyncSession, symbol: str) -> Ticker:
|
||||
return ticker
|
||||
|
||||
|
||||
def _count_price_touches(
|
||||
def _slice_tail(
|
||||
highs: list[float],
|
||||
lows: list[float],
|
||||
closes: list[float],
|
||||
volumes: list[int],
|
||||
lookback: int,
|
||||
) -> tuple[list[float], list[float], list[float], list[int]]:
|
||||
"""Return the last *lookback* bars (or all if shorter)."""
|
||||
n = len(closes)
|
||||
if lookback <= 0 or n <= lookback:
|
||||
return highs, lows, closes, volumes
|
||||
start = n - lookback
|
||||
return highs[start:], lows[start:], closes[start:], volumes[start:]
|
||||
|
||||
|
||||
def _atr_pct(
|
||||
highs: list[float],
|
||||
lows: list[float],
|
||||
closes: list[float],
|
||||
) -> float | None:
|
||||
"""ATR as a fraction of last close, or None if insufficient data."""
|
||||
try:
|
||||
result = compute_atr(highs, lows, closes)
|
||||
except ValidationError:
|
||||
return None
|
||||
atr = result["atr"]
|
||||
last = closes[-1]
|
||||
if last == 0:
|
||||
return None
|
||||
return atr / last
|
||||
|
||||
|
||||
def _merge_tolerance(
|
||||
highs: list[float],
|
||||
lows: list[float],
|
||||
closes: list[float],
|
||||
tolerance: float | None,
|
||||
) -> float:
|
||||
"""Resolve merge tolerance: explicit value or ATR-adaptive clamp."""
|
||||
if tolerance is not None:
|
||||
return tolerance
|
||||
atr_frac = _atr_pct(highs, lows, closes)
|
||||
if atr_frac is None:
|
||||
return DEFAULT_TOLERANCE
|
||||
return max(MERGE_TOL_MIN, min(MERGE_TOL_MAX, MERGE_TOL_ATR_MULT * atr_frac))
|
||||
|
||||
|
||||
def _bar_respect_weight(
|
||||
price_level: float,
|
||||
high: float,
|
||||
low: float,
|
||||
close: float,
|
||||
prev_close: float | None,
|
||||
tolerance: float,
|
||||
) -> float:
|
||||
"""Weight for how much a bar *respects* a level (not mere occupancy).
|
||||
|
||||
Only bars whose high/low **probes near the level** and closes away from
|
||||
that extreme count as rejections. Full-range pass-throughs score near zero.
|
||||
"""
|
||||
tol = price_level * tolerance if price_level != 0 else tolerance
|
||||
if tol <= 0:
|
||||
tol = abs(price_level) * DEFAULT_TOLERANCE if price_level else DEFAULT_TOLERANCE
|
||||
# Tight probe band: ~0.4% of price (capped), not 2× merge tolerance
|
||||
band = min(max(abs(price_level) * 0.004, tol * 0.35), abs(price_level) * 0.008)
|
||||
if band <= 0:
|
||||
band = abs(price_level) * 0.004 if price_level else 0.01
|
||||
|
||||
if high + band < price_level or low - band > price_level:
|
||||
return 0.0
|
||||
|
||||
bar_range = high - low
|
||||
# Support test: low probes near level, close recovers above
|
||||
support_test = abs(low - price_level) <= band and close > price_level
|
||||
if support_test and bar_range > 0:
|
||||
support_test = (close - low) >= 0.25 * bar_range
|
||||
# Resistance test: high probes near level, close rejects below
|
||||
resist_test = abs(high - price_level) <= band and close < price_level
|
||||
if resist_test and bar_range > 0:
|
||||
resist_test = (high - close) >= 0.25 * bar_range
|
||||
|
||||
if support_test or resist_test:
|
||||
return 1.0
|
||||
|
||||
# Clear directional pass-through — barely counts
|
||||
if (
|
||||
prev_close is not None
|
||||
and (prev_close - price_level) * (close - price_level) < 0
|
||||
and low < price_level - tol
|
||||
and high > price_level + tol
|
||||
):
|
||||
return 0.1
|
||||
|
||||
return 0.0
|
||||
|
||||
|
||||
def _raw_to_strength(raw: float) -> int:
|
||||
"""Map unbounded raw score to 0–100 with soft saturation (no hard pin)."""
|
||||
if raw <= 0:
|
||||
return 0
|
||||
# 1 - e^(-raw/k): raw=k → ~63, 2k → ~86, 3k → ~95
|
||||
return max(0, min(100, int(round(100.0 * (1.0 - math.exp(-raw / STRENGTH_SOFT_K))))))
|
||||
|
||||
|
||||
def _respect_evidence(
|
||||
price_level: float,
|
||||
highs: list[float],
|
||||
lows: list[float],
|
||||
closes: list[float],
|
||||
tolerance: float = DEFAULT_TOLERANCE,
|
||||
) -> int:
|
||||
"""Count how many bars touched/respected a price level within tolerance."""
|
||||
count = 0
|
||||
tol = price_level * tolerance if price_level != 0 else tolerance
|
||||
for i in range(len(closes)):
|
||||
# A bar "touches" the level if the level is within the bar's range
|
||||
# (within tolerance)
|
||||
if lows[i] - tol <= price_level <= highs[i] + tol:
|
||||
count += 1
|
||||
return count
|
||||
base: int = 0,
|
||||
half_life: float = STRENGTH_HALF_LIFE,
|
||||
lookback: int = TOUCH_LOOKBACK,
|
||||
cooldown: int = 3,
|
||||
) -> dict[str, float | int | None]:
|
||||
"""Return rejection evidence and its soft-mapped strength.
|
||||
|
||||
|
||||
def _strength_from_touches(touches: int, total_bars: int) -> int:
|
||||
"""Convert touch count to a 0-100 strength score.
|
||||
|
||||
More touches relative to total bars = higher strength.
|
||||
Cap at 100.
|
||||
*cooldown* bars after a full rejection are ignored so multi-day chop at a
|
||||
level counts as one test cluster, not N identical rejections.
|
||||
"""
|
||||
if total_bars == 0:
|
||||
return 0
|
||||
# Scale: each touch contributes proportionally, with a multiplier
|
||||
# so that a level touched ~20% of bars gets score ~100
|
||||
raw = (touches / total_bars) * 500.0
|
||||
return max(0, min(100, int(round(raw))))
|
||||
n = len(closes)
|
||||
if n == 0:
|
||||
return {
|
||||
"strength": _raw_to_strength(float(base)),
|
||||
"rejection_count": 0,
|
||||
"last_rejection_age": None,
|
||||
"weighted_respects": 0.0,
|
||||
}
|
||||
|
||||
start = max(0, n - lookback) if lookback > 0 else 0
|
||||
weighted = 0.0
|
||||
rejection_count = 0
|
||||
last_rejection_age: int | None = None
|
||||
next_ok = start
|
||||
for i in range(start, n):
|
||||
age = n - 1 - i
|
||||
decay = 0.5 ** (age / half_life) if half_life > 0 else 1.0
|
||||
prev = closes[i - 1] if i > 0 else None
|
||||
w = _bar_respect_weight(
|
||||
price_level, highs[i], lows[i], closes[i], prev, tolerance
|
||||
)
|
||||
if w >= 0.9:
|
||||
if i < next_ok:
|
||||
continue
|
||||
weighted += decay * w
|
||||
rejection_count += 1
|
||||
if last_rejection_age is None or age < last_rejection_age:
|
||||
last_rejection_age = age
|
||||
next_ok = i + max(cooldown, 1)
|
||||
elif w > 0:
|
||||
weighted += decay * w
|
||||
|
||||
raw = float(base) + weighted * STRENGTH_SCALE
|
||||
return {
|
||||
"strength": _raw_to_strength(raw),
|
||||
"rejection_count": rejection_count,
|
||||
"last_rejection_age": last_rejection_age,
|
||||
"weighted_respects": round(weighted, 6),
|
||||
}
|
||||
|
||||
|
||||
def _strength_from_respects(
|
||||
price_level: float,
|
||||
highs: list[float],
|
||||
lows: list[float],
|
||||
closes: list[float],
|
||||
tolerance: float = DEFAULT_TOLERANCE,
|
||||
base: int = 0,
|
||||
half_life: float = STRENGTH_HALF_LIFE,
|
||||
lookback: int = TOUCH_LOOKBACK,
|
||||
cooldown: int = 3,
|
||||
) -> int:
|
||||
"""Compatibility wrapper returning only the evidence-derived strength."""
|
||||
return int(_respect_evidence(
|
||||
price_level,
|
||||
highs,
|
||||
lows,
|
||||
closes,
|
||||
tolerance,
|
||||
base,
|
||||
half_life,
|
||||
lookback,
|
||||
cooldown,
|
||||
)["strength"])
|
||||
|
||||
|
||||
def _round_number_candidates(
|
||||
current_price: float,
|
||||
range_pct: float = ROUND_NUMBER_RANGE,
|
||||
max_count: int = ROUND_NUMBER_MAX,
|
||||
) -> list[float]:
|
||||
"""Psychological round levels near spot (cheap order-magnet candidates)."""
|
||||
if current_price <= 0:
|
||||
return []
|
||||
|
||||
if current_price < 5:
|
||||
steps = [0.5, 1.0]
|
||||
elif current_price < 20:
|
||||
steps = [1.0, 5.0]
|
||||
elif current_price < 100:
|
||||
steps = [5.0, 10.0, 25.0]
|
||||
elif current_price < 500:
|
||||
steps = [10.0, 25.0, 50.0, 100.0]
|
||||
else:
|
||||
steps = [25.0, 50.0, 100.0, 250.0]
|
||||
|
||||
lo = current_price * (1.0 - range_pct)
|
||||
hi = current_price * (1.0 + range_pct)
|
||||
found: set[float] = set()
|
||||
|
||||
for step in steps:
|
||||
if step <= 0:
|
||||
continue
|
||||
# Start at first multiple at or below lo
|
||||
k = math.floor(lo / step)
|
||||
while True:
|
||||
level = round(k * step, 4)
|
||||
if level > hi + step:
|
||||
break
|
||||
if lo <= level <= hi and level > 0:
|
||||
# Skip levels that are essentially current price
|
||||
if abs(level - current_price) / current_price > 0.001:
|
||||
found.add(level)
|
||||
k += 1
|
||||
if k > 1_000_000: # safety
|
||||
break
|
||||
|
||||
ordered = sorted(found, key=lambda p: abs(p - current_price))
|
||||
return ordered[:max_count]
|
||||
|
||||
|
||||
def _extract_candidate_levels(
|
||||
@@ -73,55 +306,187 @@ def _extract_candidate_levels(
|
||||
closes: list[float],
|
||||
volumes: list[int],
|
||||
) -> list[tuple[float, str]]:
|
||||
"""Extract candidate S/R levels from Volume Profile and Pivot Points.
|
||||
"""Extract candidate S/R levels from VP nodes, prominent pivots, rounds.
|
||||
|
||||
Returns list of (price_level, detection_method) tuples.
|
||||
"""
|
||||
candidates: list[tuple[float, str]] = []
|
||||
if not closes:
|
||||
return candidates
|
||||
|
||||
# Volume Profile: HVN and LVN as candidate levels
|
||||
current_price = closes[-1]
|
||||
|
||||
# --- Volume profile on recent window ---
|
||||
vp_h, vp_l, vp_c, vp_v = _slice_tail(
|
||||
highs, lows, closes, volumes, VP_LOOKBACK
|
||||
)
|
||||
try:
|
||||
vp = compute_volume_profile(highs, lows, closes, volumes)
|
||||
vp = compute_volume_profile(vp_h, vp_l, vp_c, vp_v)
|
||||
# Structural VP levels: POC, value-area edges, local HVN peaks.
|
||||
# LVN intentionally omitted (rejection voids ≠ support/resistance lines).
|
||||
for key in ("poc", "value_area_low", "value_area_high"):
|
||||
price = vp.get(key)
|
||||
if price is not None and price > 0:
|
||||
candidates.append((float(price), "volume_profile"))
|
||||
for price in vp.get("hvn", []):
|
||||
candidates.append((price, "volume_profile"))
|
||||
for price in vp.get("lvn", []):
|
||||
candidates.append((price, "volume_profile"))
|
||||
candidates.append((float(price), "volume_profile"))
|
||||
except ValidationError:
|
||||
pass # Not enough data for volume profile
|
||||
pass
|
||||
|
||||
# --- Prominent pivots on pivot lookback ---
|
||||
p_h, p_l, p_c, _ = _slice_tail(highs, lows, closes, volumes, PIVOT_LOOKBACK)
|
||||
atr_frac = _atr_pct(p_h, p_l, p_c)
|
||||
last = p_c[-1] if p_c else current_price
|
||||
if atr_frac is not None and last > 0:
|
||||
prominence = max(PIVOT_PROMINENCE_ATR * atr_frac * last, PIVOT_PROMINENCE_PCT * last)
|
||||
else:
|
||||
prominence = PIVOT_PROMINENCE_PCT * last if last > 0 else None
|
||||
|
||||
# Pivot Points: swing highs and lows
|
||||
try:
|
||||
pp = compute_pivot_points(highs, lows, closes)
|
||||
pp = compute_pivot_points(p_h, p_l, p_c, min_prominence=prominence)
|
||||
for price in pp.get("swing_highs", []):
|
||||
candidates.append((price, "pivot_point"))
|
||||
candidates.append((float(price), "pivot_point"))
|
||||
for price in pp.get("swing_lows", []):
|
||||
candidates.append((price, "pivot_point"))
|
||||
candidates.append((float(price), "pivot_point"))
|
||||
except ValidationError:
|
||||
pass # Not enough data for pivot points
|
||||
pass
|
||||
|
||||
# --- Psychological round numbers near spot ---
|
||||
for price in _round_number_candidates(current_price):
|
||||
candidates.append((price, "round_number"))
|
||||
|
||||
return candidates
|
||||
|
||||
|
||||
def _gate_target_range_centers(
|
||||
highs: list[float],
|
||||
lows: list[float],
|
||||
closes: list[float],
|
||||
num_bins: int = 20,
|
||||
) -> list[float]:
|
||||
"""Return the evenly spaced price proposals used by the production GTL."""
|
||||
if len(closes) < 20:
|
||||
raise ValidationError(
|
||||
f"Range grid requires at least 20 bars, got {len(closes)}"
|
||||
)
|
||||
price_min = min(lows)
|
||||
price_max = max(highs)
|
||||
if price_max == price_min:
|
||||
price_max = price_min + 1.0
|
||||
bin_width = (price_max - price_min) / num_bins
|
||||
return [
|
||||
round(price_min + (i + 0.5) * bin_width, 4)
|
||||
for i in range(num_bins)
|
||||
]
|
||||
|
||||
|
||||
def detect_gate_target_ladder(
|
||||
highs: list[float],
|
||||
lows: list[float],
|
||||
closes: list[float],
|
||||
tolerance: float = DEFAULT_TOLERANCE,
|
||||
) -> list[dict]:
|
||||
"""Build the scanner's internal, volume-free target proposal ladder.
|
||||
|
||||
This is intentionally not human-facing support/resistance. It builds the
|
||||
production gate's broad 20-bin range grid, adds unfiltered pivots, scores
|
||||
historical price traffic, and merges nearby proposals. The returned levels
|
||||
are transient and must not be persisted as chart S/R.
|
||||
"""
|
||||
if not closes:
|
||||
return []
|
||||
|
||||
candidates: list[tuple[float, str]] = []
|
||||
try:
|
||||
candidates.extend(
|
||||
(float(price), "range_grid")
|
||||
for price in _gate_target_range_centers(highs, lows, closes)
|
||||
)
|
||||
except ValidationError:
|
||||
pass
|
||||
try:
|
||||
pivots = compute_pivot_points(highs, lows, closes)
|
||||
candidates.extend(
|
||||
(float(price), "pivot_point")
|
||||
for price in pivots.get("swing_highs", []) + pivots.get("swing_lows", [])
|
||||
)
|
||||
except ValidationError:
|
||||
pass
|
||||
if not candidates:
|
||||
return []
|
||||
|
||||
total_bars = len(closes)
|
||||
raw: list[dict] = []
|
||||
for price, method in candidates:
|
||||
tol = price * tolerance if price != 0 else tolerance
|
||||
touches = sum(
|
||||
1 for low, high in zip(lows, highs, strict=False)
|
||||
if low - tol <= price <= high + tol
|
||||
)
|
||||
strength = max(0, min(100, int(round((touches / total_bars) * 500.0))))
|
||||
raw.append({
|
||||
"price_level": price,
|
||||
"strength": strength,
|
||||
"detection_method": method,
|
||||
"type": "",
|
||||
"sources": [method],
|
||||
"rejection_count": touches,
|
||||
"last_rejection_age": None,
|
||||
"weighted_respects": float(touches),
|
||||
})
|
||||
|
||||
merged: list[dict] = []
|
||||
for level in sorted(raw, key=lambda row: row["price_level"]):
|
||||
if not merged:
|
||||
merged.append(dict(level))
|
||||
continue
|
||||
last = merged[-1]
|
||||
ref = last["price_level"]
|
||||
tol = ref * tolerance if ref != 0 else tolerance
|
||||
if abs(level["price_level"] - ref) > tol:
|
||||
merged.append(dict(level))
|
||||
continue
|
||||
last["price_level"] = round(
|
||||
(last["price_level"] + level["price_level"]) / 2.0, 4
|
||||
)
|
||||
last["strength"] = min(100, last["strength"] + level["strength"])
|
||||
sources = set(last.get("sources") or [last["detection_method"]])
|
||||
sources |= set(level.get("sources") or [level["detection_method"]])
|
||||
last["sources"] = sorted(sources)
|
||||
last["detection_method"] = (
|
||||
next(iter(sources)) if len(sources) == 1 else "merged"
|
||||
)
|
||||
last["rejection_count"] = max(
|
||||
int(last.get("rejection_count", 0)),
|
||||
int(level.get("rejection_count", 0)),
|
||||
)
|
||||
|
||||
_tag_levels(merged, closes[-1])
|
||||
merged.sort(key=lambda row: row["strength"], reverse=True)
|
||||
return merged
|
||||
|
||||
|
||||
def _merge_levels(
|
||||
levels: list[dict],
|
||||
tolerance: float = DEFAULT_TOLERANCE,
|
||||
) -> list[dict]:
|
||||
"""Merge levels within tolerance into consolidated levels.
|
||||
|
||||
Levels from different methods within tolerance are merged.
|
||||
Merged levels combine strength scores (capped at 100) and get
|
||||
detection_method = "merged".
|
||||
Strength combines via max + partial min (avoids instant saturation) with
|
||||
a confluence bonus when detection methods differ. Price is strength-weighted.
|
||||
"""
|
||||
if not levels:
|
||||
return []
|
||||
|
||||
# Sort by price
|
||||
sorted_levels = sorted(levels, key=lambda x: x["price_level"])
|
||||
merged: list[dict] = []
|
||||
|
||||
for level in sorted_levels:
|
||||
if not merged:
|
||||
merged.append(dict(level))
|
||||
entry = dict(level)
|
||||
sources = level.get("sources") or [level["detection_method"]]
|
||||
entry["sources"] = sorted(set(sources))
|
||||
merged.append(entry)
|
||||
continue
|
||||
|
||||
last = merged[-1]
|
||||
@@ -129,19 +494,52 @@ def _merge_levels(
|
||||
tol = ref_price * tolerance if ref_price != 0 else tolerance
|
||||
|
||||
if abs(level["price_level"] - ref_price) <= tol:
|
||||
# Merge: average price, combine strength, mark as merged
|
||||
combined_strength = min(100, last["strength"] + level["strength"])
|
||||
avg_price = (last["price_level"] + level["price_level"]) / 2.0
|
||||
method = (
|
||||
"merged"
|
||||
if last["detection_method"] != level["detection_method"]
|
||||
else last["detection_method"]
|
||||
)
|
||||
s1 = last["strength"]
|
||||
s2 = level["strength"]
|
||||
# Soft combine — avoid merge math pinning everything at 100
|
||||
combined = int(round(0.85 * max(s1, s2) + 0.15 * min(s1, s2)))
|
||||
sources = set(last.get("sources") or [last["detection_method"]])
|
||||
sources |= set(level.get("sources") or [level["detection_method"]])
|
||||
if len(sources) > 1:
|
||||
combined = min(100, combined + 5)
|
||||
else:
|
||||
combined = min(100, combined)
|
||||
|
||||
w1, w2 = max(s1, 1), max(s2, 1)
|
||||
avg_price = (last["price_level"] * w1 + level["price_level"] * w2) / (w1 + w2)
|
||||
|
||||
if len(sources) == 1:
|
||||
method = next(iter(sources))
|
||||
else:
|
||||
method = "merged"
|
||||
|
||||
last["price_level"] = round(avg_price, 4)
|
||||
last["strength"] = combined_strength
|
||||
last["strength"] = combined
|
||||
last["detection_method"] = method
|
||||
last["sources"] = sorted(sources)
|
||||
# Nearby candidates often describe the same price reaction, so do
|
||||
# not add their rejection counts and double-count one market event.
|
||||
last["rejection_count"] = max(
|
||||
int(last.get("rejection_count", 0)),
|
||||
int(level.get("rejection_count", 0)),
|
||||
)
|
||||
ages = [
|
||||
age for age in (
|
||||
last.get("last_rejection_age"),
|
||||
level.get("last_rejection_age"),
|
||||
)
|
||||
if age is not None
|
||||
]
|
||||
last["last_rejection_age"] = min(ages) if ages else None
|
||||
last["weighted_respects"] = max(
|
||||
float(last.get("weighted_respects", 0.0)),
|
||||
float(level.get("weighted_respects", 0.0)),
|
||||
)
|
||||
else:
|
||||
merged.append(dict(level))
|
||||
entry = dict(level)
|
||||
sources = level.get("sources") or [level["detection_method"]]
|
||||
entry["sources"] = sorted(set(sources))
|
||||
merged.append(entry)
|
||||
|
||||
return merged
|
||||
|
||||
@@ -159,14 +557,66 @@ def _tag_levels(
|
||||
return levels
|
||||
|
||||
|
||||
def _cap_levels(
|
||||
levels: list[dict],
|
||||
max_levels: int = MAX_LEVELS,
|
||||
) -> list[dict]:
|
||||
"""Keep up to *max_levels* levels, interleaving support/resistance by strength."""
|
||||
if max_levels <= 0 or len(levels) <= max_levels:
|
||||
return levels
|
||||
|
||||
support = sorted(
|
||||
[lvl for lvl in levels if lvl.get("type") == "support"],
|
||||
key=lambda x: x["strength"],
|
||||
reverse=True,
|
||||
)
|
||||
resistance = sorted(
|
||||
[lvl for lvl in levels if lvl.get("type") != "support"],
|
||||
key=lambda x: x["strength"],
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
selected: list[dict] = []
|
||||
si, ri = 0, 0
|
||||
pick_support = True
|
||||
while len(selected) < max_levels and (si < len(support) or ri < len(resistance)):
|
||||
if pick_support:
|
||||
if si < len(support):
|
||||
selected.append(support[si])
|
||||
si += 1
|
||||
elif ri < len(resistance):
|
||||
selected.append(resistance[ri])
|
||||
ri += 1
|
||||
else:
|
||||
if ri < len(resistance):
|
||||
selected.append(resistance[ri])
|
||||
ri += 1
|
||||
elif si < len(support):
|
||||
selected.append(support[si])
|
||||
si += 1
|
||||
pick_support = not pick_support
|
||||
|
||||
selected.sort(key=lambda x: x["strength"], reverse=True)
|
||||
return selected
|
||||
|
||||
|
||||
def detect_sr_levels(
|
||||
highs: list[float],
|
||||
lows: list[float],
|
||||
closes: list[float],
|
||||
volumes: list[int],
|
||||
tolerance: float = DEFAULT_TOLERANCE,
|
||||
tolerance: float | None = None,
|
||||
max_levels: int = MAX_LEVELS,
|
||||
) -> list[dict]:
|
||||
"""Detect, score, merge, and tag S/R levels from OHLCV data.
|
||||
"""Detect, score, merge, tag, and cap S/R levels from OHLCV data.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
tolerance:
|
||||
Relative merge tolerance. ``None`` (default) uses ATR-adaptive
|
||||
tolerance clamped to [0.4%, 1.5%]. Pass an explicit fraction to override.
|
||||
max_levels:
|
||||
Hard cap after merge (balanced support/resistance). 0 = no cap.
|
||||
|
||||
Returns list of dicts with keys: price_level, type, strength,
|
||||
detection_method — sorted by strength descending.
|
||||
@@ -178,37 +628,42 @@ def detect_sr_levels(
|
||||
if not candidates:
|
||||
return []
|
||||
|
||||
total_bars = len(closes)
|
||||
current_price = closes[-1]
|
||||
merge_tol = _merge_tolerance(highs, lows, closes, tolerance)
|
||||
# Touch tolerance for strength: use merge tol (same price scale)
|
||||
touch_tol = merge_tol
|
||||
|
||||
# Build level dicts with strength scores
|
||||
# Score each candidate on recent rejection-weighted touches
|
||||
raw_levels: list[dict] = []
|
||||
for price, method in candidates:
|
||||
touches = _count_price_touches(price, highs, lows, closes, tolerance)
|
||||
strength = _strength_from_touches(touches, total_bars)
|
||||
base = _METHOD_BASE_STRENGTH.get(method, 0)
|
||||
evidence = _respect_evidence(
|
||||
price, highs, lows, closes, touch_tol, base=base
|
||||
)
|
||||
raw_levels.append({
|
||||
"price_level": price,
|
||||
"strength": strength,
|
||||
"strength": int(evidence["strength"]),
|
||||
"detection_method": method,
|
||||
"type": "", # will be tagged after merge
|
||||
"type": "",
|
||||
"sources": [method],
|
||||
"rejection_count": int(evidence["rejection_count"]),
|
||||
"last_rejection_age": evidence["last_rejection_age"],
|
||||
"weighted_respects": float(evidence["weighted_respects"]),
|
||||
})
|
||||
|
||||
# Merge nearby levels
|
||||
merged = _merge_levels(raw_levels, tolerance)
|
||||
|
||||
# Tag as support/resistance
|
||||
merged = _merge_levels(raw_levels, merge_tol)
|
||||
tagged = _tag_levels(merged, current_price)
|
||||
capped = _cap_levels(tagged, max_levels=max_levels)
|
||||
capped.sort(key=lambda x: x["strength"], reverse=True)
|
||||
return capped
|
||||
|
||||
# Sort by strength descending
|
||||
tagged.sort(key=lambda x: x["strength"], reverse=True)
|
||||
|
||||
return tagged
|
||||
|
||||
def cluster_sr_zones(
|
||||
levels: list[dict],
|
||||
current_price: float,
|
||||
tolerance: float = 0.02,
|
||||
max_zones: int | None = None,
|
||||
strength_mode: str = "sum",
|
||||
) -> list[dict]:
|
||||
"""Cluster nearby S/R levels into zones.
|
||||
|
||||
@@ -263,8 +718,26 @@ def cluster_sr_zones(
|
||||
low = min(prices)
|
||||
high = max(prices)
|
||||
midpoint = (low + high) / 2.0
|
||||
strength = min(100, sum(lvl["strength"] for lvl in cluster))
|
||||
if strength_mode == "soft":
|
||||
strongest = max(int(lvl["strength"]) for lvl in cluster)
|
||||
all_sources = {
|
||||
source
|
||||
for lvl in cluster
|
||||
for source in (lvl.get("sources") or [lvl.get("detection_method", "unknown")])
|
||||
}
|
||||
strength = min(100, strongest + (5 if len(all_sources) > 1 else 0))
|
||||
elif strength_mode == "sum":
|
||||
strength = min(100, sum(int(lvl["strength"]) for lvl in cluster))
|
||||
all_sources = {
|
||||
source
|
||||
for lvl in cluster
|
||||
for source in (lvl.get("sources") or [lvl.get("detection_method", "unknown")])
|
||||
}
|
||||
else:
|
||||
raise ValueError(f"Unsupported S/R zone strength mode: {strength_mode}")
|
||||
level_count = len(cluster)
|
||||
rejection_count = max(int(lvl.get("rejection_count", 0)) for lvl in cluster)
|
||||
ages = [lvl.get("last_rejection_age") for lvl in cluster if lvl.get("last_rejection_age") is not None]
|
||||
|
||||
# 4. Tag zone type
|
||||
zone_type = "support" if midpoint < current_price else "resistance"
|
||||
@@ -276,6 +749,9 @@ def cluster_sr_zones(
|
||||
"strength": strength,
|
||||
"type": zone_type,
|
||||
"level_count": level_count,
|
||||
"sources": sorted(all_sources),
|
||||
"rejection_count": rejection_count,
|
||||
"last_rejection_age": min(ages) if ages else None,
|
||||
})
|
||||
|
||||
# 5. Split into support and resistance pools, each sorted by strength desc
|
||||
@@ -319,11 +795,10 @@ def cluster_sr_zones(
|
||||
return selected
|
||||
|
||||
|
||||
|
||||
async def recalculate_sr_levels(
|
||||
db: AsyncSession,
|
||||
symbol: str,
|
||||
tolerance: float = DEFAULT_TOLERANCE,
|
||||
tolerance: float | None = None,
|
||||
) -> list[SRLevel]:
|
||||
"""Recalculate S/R levels for a ticker and persist to DB.
|
||||
|
||||
@@ -380,10 +855,44 @@ async def recalculate_sr_levels(
|
||||
async def get_sr_levels(
|
||||
db: AsyncSession,
|
||||
symbol: str,
|
||||
tolerance: float = DEFAULT_TOLERANCE,
|
||||
tolerance: float | None = None,
|
||||
) -> list[SRLevel]:
|
||||
"""Get S/R levels for a ticker, recalculating on every request (MVP).
|
||||
"""Return Structural S/R for a ticker, strength descending.
|
||||
|
||||
Returns levels sorted by strength descending.
|
||||
Default (``tolerance is None``): read persisted levels only — no rewrite.
|
||||
Pipeline/ingestion call ``recalculate_sr_levels`` after OHLCV changes.
|
||||
|
||||
When ``tolerance`` is set: build a **transient** detect view with that merge
|
||||
tolerance and do not persist it (custom merge for API clients). Transient
|
||||
rows use negative ids so they cannot be confused with stored levels.
|
||||
"""
|
||||
return await recalculate_sr_levels(db, symbol, tolerance)
|
||||
if tolerance is None:
|
||||
ticker = await _get_ticker(db, symbol)
|
||||
result = await db.execute(
|
||||
select(SRLevel)
|
||||
.where(SRLevel.ticker_id == ticker.id)
|
||||
.order_by(SRLevel.strength.desc())
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
ticker = await _get_ticker(db, symbol)
|
||||
records = await query_ohlcv(db, symbol)
|
||||
if not records:
|
||||
return []
|
||||
_, highs, lows, closes, volumes = _extract_ohlcv(records)
|
||||
detected = detect_sr_levels(highs, lows, closes, volumes, tolerance)
|
||||
now = datetime.utcnow()
|
||||
# Ephemeral objects with the SRLevel attribute shape the router expects.
|
||||
return [
|
||||
SimpleNamespace( # type: ignore[return-value]
|
||||
id=-(i + 1),
|
||||
price_level=lvl["price_level"],
|
||||
type=lvl["type"],
|
||||
strength=lvl["strength"],
|
||||
detection_method=lvl["detection_method"],
|
||||
created_at=now,
|
||||
)
|
||||
for i, lvl in enumerate(detected)
|
||||
]
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Persist and query operational system events (warnings / errors)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.system_event import SystemEvent
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_LOOKBACK_DAYS = 7
|
||||
DEFAULT_DEDUP_HOURS = 24
|
||||
SEVERITIES = frozenset({"warning", "error"})
|
||||
|
||||
|
||||
async def log_event(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
severity: str,
|
||||
source: str,
|
||||
code: str,
|
||||
message: str,
|
||||
symbol: str | None = None,
|
||||
dedup_key: str | None = None,
|
||||
dedup_hours: int = DEFAULT_DEDUP_HOURS,
|
||||
) -> SystemEvent | None:
|
||||
"""Insert a system event, optionally de-duplicating recent identical keys.
|
||||
|
||||
Returns the new row, or None when a recent dedup_key already exists.
|
||||
Commits the session.
|
||||
"""
|
||||
severity = (severity or "").strip().lower()
|
||||
if severity not in SEVERITIES:
|
||||
severity = "warning"
|
||||
source = (source or "system")[:64]
|
||||
code = (code or "unknown")[:64]
|
||||
message = (message or "").strip() or code
|
||||
symbol = symbol.strip().upper()[:20] if symbol else None
|
||||
dedup_key = dedup_key[:200] if dedup_key else None
|
||||
|
||||
if dedup_key:
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(hours=max(1, dedup_hours))
|
||||
existing = await db.execute(
|
||||
select(SystemEvent.id)
|
||||
.where(
|
||||
SystemEvent.dedup_key == dedup_key,
|
||||
SystemEvent.created_at >= cutoff,
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
if existing.scalar_one_or_none() is not None:
|
||||
return None
|
||||
|
||||
row = SystemEvent(
|
||||
severity=severity,
|
||||
source=source,
|
||||
code=code,
|
||||
message=message[:4000],
|
||||
symbol=symbol,
|
||||
dedup_key=dedup_key,
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
db.add(row)
|
||||
await db.commit()
|
||||
await db.refresh(row)
|
||||
return row
|
||||
|
||||
|
||||
async def log_event_standalone(
|
||||
*,
|
||||
severity: str,
|
||||
source: str,
|
||||
code: str,
|
||||
message: str,
|
||||
symbol: str | None = None,
|
||||
dedup_key: str | None = None,
|
||||
) -> None:
|
||||
"""Open a short-lived session and log an event (for scheduler / fire-and-forget)."""
|
||||
try:
|
||||
from app.database import async_session_factory
|
||||
|
||||
async with async_session_factory() as db:
|
||||
await log_event(
|
||||
db,
|
||||
severity=severity,
|
||||
source=source,
|
||||
code=code,
|
||||
message=message,
|
||||
symbol=symbol,
|
||||
dedup_key=dedup_key,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed to persist system event %s/%s", source, code)
|
||||
|
||||
|
||||
async def list_events(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
days: int = DEFAULT_LOOKBACK_DAYS,
|
||||
severity: str | None = None,
|
||||
unacknowledged_only: bool = False,
|
||||
limit: int = 200,
|
||||
) -> list[SystemEvent]:
|
||||
days = max(1, min(int(days), 30))
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
|
||||
stmt = (
|
||||
select(SystemEvent)
|
||||
.where(SystemEvent.created_at >= cutoff)
|
||||
.order_by(SystemEvent.created_at.desc())
|
||||
.limit(max(1, min(limit, 500)))
|
||||
)
|
||||
if severity in SEVERITIES:
|
||||
stmt = stmt.where(SystemEvent.severity == severity)
|
||||
if unacknowledged_only:
|
||||
stmt = stmt.where(SystemEvent.acknowledged_at.is_(None))
|
||||
result = await db.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def summary(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
days: int = DEFAULT_LOOKBACK_DAYS,
|
||||
) -> dict:
|
||||
"""Counts for badge + admin header."""
|
||||
days = max(1, min(int(days), 30))
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(SystemEvent.severity, SystemEvent.acknowledged_at).where(
|
||||
SystemEvent.created_at >= cutoff
|
||||
)
|
||||
)
|
||||
).all()
|
||||
total = len(rows)
|
||||
unacked = 0
|
||||
errors = 0
|
||||
warnings = 0
|
||||
for severity, acknowledged_at in rows:
|
||||
if acknowledged_at is not None:
|
||||
continue
|
||||
unacked += 1
|
||||
if severity == "error":
|
||||
errors += 1
|
||||
elif severity == "warning":
|
||||
warnings += 1
|
||||
return {
|
||||
"days": days,
|
||||
"total": total,
|
||||
"unacknowledged": unacked,
|
||||
"unacknowledged_errors": errors,
|
||||
"unacknowledged_warnings": warnings,
|
||||
}
|
||||
|
||||
|
||||
async def acknowledge_all(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
days: int = DEFAULT_LOOKBACK_DAYS,
|
||||
) -> int:
|
||||
"""Mark unacknowledged events in the lookback window as dismissed. Returns count."""
|
||||
days = max(1, min(int(days), 30))
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
|
||||
now = datetime.now(timezone.utc)
|
||||
result = await db.execute(
|
||||
update(SystemEvent)
|
||||
.where(
|
||||
SystemEvent.created_at >= cutoff,
|
||||
SystemEvent.acknowledged_at.is_(None),
|
||||
)
|
||||
.values(acknowledged_at=now)
|
||||
)
|
||||
await db.commit()
|
||||
return int(result.rowcount or 0)
|
||||
|
||||
|
||||
def event_to_dict(row: SystemEvent) -> dict:
|
||||
return {
|
||||
"id": row.id,
|
||||
"severity": row.severity,
|
||||
"source": row.source,
|
||||
"code": row.code,
|
||||
"message": row.message,
|
||||
"symbol": row.symbol,
|
||||
"created_at": row.created_at.isoformat() if row.created_at else None,
|
||||
"acknowledged_at": row.acknowledged_at.isoformat() if row.acknowledged_at else None,
|
||||
}
|
||||
@@ -1,13 +1,65 @@
|
||||
"""Ticker Registry service: add, delete, and list tracked tickers."""
|
||||
"""Ticker Registry service: add, delete, list, and retire tracked tickers."""
|
||||
|
||||
import logging
|
||||
import re
|
||||
from datetime import date, timedelta
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func, or_, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.exceptions import DuplicateError, NotFoundError, ValidationError
|
||||
from app.models.ticker import Ticker
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Reasons a symbol may be marked delisted, narrowest first.
|
||||
REASON_FORM_25 = "form_25" # SEC Form 25/25-NSE/15 confirmed the exchange exit
|
||||
REASON_MANUAL = "manual" # an operator decided
|
||||
|
||||
# How long a symbol must be without bars before we spend an SEC request asking
|
||||
# whether it delisted. Guards against a market-data outage probing the whole
|
||||
# universe at once; a real delisting is still stale days later.
|
||||
MIN_STALE_DAYS_BEFORE_PROBE = 3
|
||||
|
||||
# Rule 12d2-2: a Form 25 removal takes effect ten days after filing, so the
|
||||
# filing date is not the date the security stopped trading.
|
||||
FORM_25_EFFECTIVE_DAYS = 10
|
||||
|
||||
# How far before the last bar a Form 25 may be filed and still explain this gap.
|
||||
# An exchange can file shortly before trading actually stops; anything older
|
||||
# concerns a class that was already gone while the symbol kept printing bars.
|
||||
FILING_LOOKBACK_DAYS = 30
|
||||
|
||||
|
||||
def _sec_client_factory():
|
||||
"""Build the SEC client for a delisting probe (patched in tests).
|
||||
|
||||
Imported lazily so the SEC/httpx stack stays off the import path of every
|
||||
module that only wants ``active_only``.
|
||||
"""
|
||||
from app.services.sec_client import SecClient
|
||||
|
||||
return SecClient()
|
||||
|
||||
|
||||
def active_only(stmt, *, as_of: date | None = None):
|
||||
"""Restrict a Ticker query to symbols that still trade.
|
||||
|
||||
Opt-in on purpose rather than folded into a shared getter: list and admin
|
||||
views deliberately keep delisted rows so the delisting is *visible*, which a
|
||||
silent default would undo. Apply this on the live signal path — scanning,
|
||||
ranking, scoring, breadth, ingestion — and nowhere else.
|
||||
|
||||
``delisted_on`` is an *effective* date, and a Form 25 is known ten days
|
||||
before it takes effect, so a future date must not drop the symbol yet — it
|
||||
is still trading and still worth scanning and ingesting. Compared in SQL
|
||||
against the database's own date; ``as_of`` overrides it for tests.
|
||||
"""
|
||||
cutoff = func.current_date() if as_of is None else as_of
|
||||
return stmt.where(
|
||||
or_(Ticker.delisted_on.is_(None), Ticker.delisted_on > cutoff)
|
||||
)
|
||||
|
||||
|
||||
async def add_ticker(db: AsyncSession, symbol: str) -> Ticker:
|
||||
"""Add a new ticker after validation.
|
||||
@@ -52,6 +104,150 @@ async def delete_ticker(db: AsyncSession, symbol: str) -> None:
|
||||
|
||||
|
||||
async def list_tickers(db: AsyncSession) -> list[Ticker]:
|
||||
"""Return all tracked tickers sorted alphabetically by symbol."""
|
||||
"""Return all tracked tickers sorted alphabetically by symbol.
|
||||
|
||||
Delisted symbols are included and carry ``delisted_on`` — the registry is
|
||||
where an operator needs to *see* that a symbol retired, not where it should
|
||||
quietly disappear.
|
||||
"""
|
||||
result = await db.execute(select(Ticker).order_by(Ticker.symbol.asc()))
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def mark_delisted(
|
||||
db: AsyncSession,
|
||||
symbol: str,
|
||||
*,
|
||||
delisted_on: date,
|
||||
reason: str = REASON_MANUAL,
|
||||
) -> bool:
|
||||
"""Record that a symbol stopped trading. True if this changed anything.
|
||||
|
||||
Idempotent, so the staleness path can call it every run without churning the
|
||||
row: re-marking is a no-op. The one exception is an SEC confirmation landing
|
||||
on a row an operator marked by hand — Form 25 carries the real effective
|
||||
date, so it replaces the operator's estimate. Nothing downgrades a confirmed
|
||||
row back to a manual one.
|
||||
"""
|
||||
normalised = symbol.strip().upper()
|
||||
result = await db.execute(select(Ticker).where(Ticker.symbol == normalised))
|
||||
ticker = result.scalar_one_or_none()
|
||||
if ticker is None:
|
||||
raise NotFoundError(f"Ticker not found: {normalised}")
|
||||
if ticker.delisted_on is not None:
|
||||
upgrading = (
|
||||
reason == REASON_FORM_25 and ticker.delisted_reason != REASON_FORM_25
|
||||
)
|
||||
if not upgrading:
|
||||
return False
|
||||
|
||||
await db.execute(
|
||||
update(Ticker)
|
||||
.where(Ticker.id == ticker.id)
|
||||
.values(delisted_on=delisted_on, delisted_reason=reason)
|
||||
)
|
||||
await db.commit()
|
||||
logger.info(
|
||||
"ticker %s marked delisted on %s (%s)", normalised, delisted_on, reason
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
async def confirm_delisting(
|
||||
db: AsyncSession,
|
||||
symbol: str,
|
||||
*,
|
||||
last_bar: date | None,
|
||||
today: date | None = None,
|
||||
) -> date | None:
|
||||
"""Ask SEC whether ``symbol`` actually delisted; mark it if so.
|
||||
|
||||
Called when OHLCV goes stale, because "no new bars" alone cannot tell a
|
||||
delisting from a halt or a rename. Returns the effective date whenever the
|
||||
symbol is known to have delisted — whether this call established that or an
|
||||
earlier one did — and ``None`` while it remains unproven, so the caller warns
|
||||
only about gaps that still have no explanation.
|
||||
|
||||
Returning the already-known date matters between filing and effect: trading
|
||||
usually stops before the ten-day Rule 12d2-2 delay expires, so the symbol is
|
||||
correctly still active (see ``active_only``) while producing no bars. Without
|
||||
this the staleness warning would fire daily across that window — the exact
|
||||
noise the delisting flow exists to remove.
|
||||
|
||||
Deliberately driven by staleness rather than by the SEC fundamentals import:
|
||||
that importer stalls for days at a time on unrelated Company-Facts gaps, and
|
||||
detection wired into it would stall with it.
|
||||
|
||||
The probe waits for ``MIN_STALE_DAYS_BEFORE_PROBE``. A delisted symbol stays
|
||||
stale forever, so the delay costs nothing, and it keeps a broad market-data
|
||||
outage — where every tracked symbol reports stale at once — from turning into
|
||||
one SEC request per symbol per run.
|
||||
"""
|
||||
from app.services.sec_client import SecError
|
||||
|
||||
normalised = symbol.strip().upper()
|
||||
result = await db.execute(select(Ticker).where(Ticker.symbol == normalised))
|
||||
ticker = result.scalar_one_or_none()
|
||||
if ticker is None:
|
||||
return None
|
||||
known = ticker.delisted_on
|
||||
# Already confirmed by SEC — nothing left to learn, but the caller still
|
||||
# needs the date to know this gap is explained. A row an operator marked by
|
||||
# hand is worth probing: Form 25 upgrades the estimated date.
|
||||
if ticker.delisted_reason == REASON_FORM_25:
|
||||
return known
|
||||
if not ticker.cik:
|
||||
return known
|
||||
# No bars at all is an ingestion problem, not evidence of a delisting.
|
||||
if last_bar is None:
|
||||
return known
|
||||
if ((today or date.today()) - last_bar).days < MIN_STALE_DAYS_BEFORE_PROBE:
|
||||
return known
|
||||
|
||||
try:
|
||||
async with _sec_client_factory() as client:
|
||||
# Only a Form 25 filed around or after the last bar can explain THIS
|
||||
# gap. An older one belongs to a class that stopped trading before
|
||||
# the symbol was still printing bars, and must not retire it.
|
||||
filing = await client.delisting_filing(
|
||||
ticker.cik, not_before=last_bar - timedelta(days=FILING_LOOKBACK_DAYS)
|
||||
)
|
||||
except SecError:
|
||||
# Never let a probe failure escalate a routine staleness warning.
|
||||
logger.warning("delisting probe failed for %s", normalised, exc_info=True)
|
||||
return known
|
||||
|
||||
if filing is None:
|
||||
return known
|
||||
# Removal takes effect ten days after filing, so the filing date is not the
|
||||
# date the symbol stopped trading.
|
||||
effective = filing["filing_date"] + timedelta(days=FORM_25_EFFECTIVE_DAYS)
|
||||
if await mark_delisted(
|
||||
db, normalised, delisted_on=effective, reason=REASON_FORM_25
|
||||
):
|
||||
return effective
|
||||
return known
|
||||
|
||||
|
||||
async def clear_delisted(db: AsyncSession, symbol: str) -> bool:
|
||||
"""Un-retire a symbol. True if it had been marked.
|
||||
|
||||
The counterpart that makes automatic marking acceptable: a false positive
|
||||
costs one row update, where a delete would have cost the price history.
|
||||
"""
|
||||
normalised = symbol.strip().upper()
|
||||
result = await db.execute(select(Ticker).where(Ticker.symbol == normalised))
|
||||
ticker = result.scalar_one_or_none()
|
||||
if ticker is None:
|
||||
raise NotFoundError(f"Ticker not found: {normalised}")
|
||||
if ticker.delisted_on is None:
|
||||
return False
|
||||
|
||||
await db.execute(
|
||||
update(Ticker)
|
||||
.where(Ticker.id == ticker.id)
|
||||
.values(delisted_on=None, delisted_reason=None)
|
||||
)
|
||||
await db.commit()
|
||||
logger.info("ticker %s un-marked as delisted", normalised)
|
||||
return True
|
||||
|
||||
@@ -55,6 +55,43 @@ if not _CA_BUNDLE or not Path(_CA_BUNDLE).exists():
|
||||
else:
|
||||
_CA_BUNDLE_PATH = _CA_BUNDLE
|
||||
|
||||
# Wikipedia often returns 403 to non-browser UAs; use a normal browser-like
|
||||
# identity for constituent scrapes (no cookies/login).
|
||||
_HTTP_HEADERS = {
|
||||
"User-Agent": (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/126.0.0.0 Safari/537.36"
|
||||
),
|
||||
"Accept": "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",
|
||||
"Accept-Language": "en-US,en;q=0.9",
|
||||
}
|
||||
|
||||
# Modern Wikipedia S&P/Nasdaq tables use exchange templates (NyseSymbol /
|
||||
# NasdaqSymbol) rather than a plain <td><a>SYMBOL</a></td>. Prefer quote URLs
|
||||
# and template params; keep the legacy cell pattern as a last resort.
|
||||
_WIKI_SYMBOL_PATTERNS: tuple[re.Pattern[str], ...] = (
|
||||
re.compile(r"nyse\.com/quote/XNYS:([A-Za-z0-9.-]{1,10})", re.IGNORECASE),
|
||||
re.compile(
|
||||
r"nasdaq\.com/market-activity/stocks/([A-Za-z0-9.-]{1,10})",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
# {{NyseSymbol|BNY}} / {{NasdaqSymbol|AAPL}} rendered data-mw params
|
||||
re.compile(
|
||||
r'"target":\{"wt":"(?:Nyse|Nasdaq)Symbol"[^}]*\}.*"wt":"([A-Z][A-Z0-9.-]{0,9})"',
|
||||
re.IGNORECASE,
|
||||
),
|
||||
re.compile(r"<td>\s*<a[^>]*>([A-Z.]{1,10})</a>\s*</td>", re.IGNORECASE),
|
||||
)
|
||||
|
||||
|
||||
def _extract_wiki_symbols(html: str) -> list[str]:
|
||||
"""Pull ticker symbols out of a Wikipedia constituents page."""
|
||||
found: list[str] = []
|
||||
for pattern in _WIKI_SYMBOL_PATTERNS:
|
||||
found.extend(pattern.findall(html))
|
||||
return found
|
||||
|
||||
|
||||
def _validate_universe(universe: str) -> str:
|
||||
normalised = universe.strip().lower()
|
||||
@@ -76,130 +113,19 @@ def _normalise_symbols(symbols: Iterable[str]) -> list[str]:
|
||||
return sorted(deduped)
|
||||
|
||||
|
||||
def _extract_symbols_from_fmp_payload(payload: object) -> list[str]:
|
||||
if not isinstance(payload, list):
|
||||
return []
|
||||
|
||||
symbols: list[str] = []
|
||||
for item in payload:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
candidate = item.get("symbol") or item.get("ticker")
|
||||
if isinstance(candidate, str):
|
||||
symbols.append(candidate)
|
||||
return symbols
|
||||
|
||||
|
||||
async def _try_fmp_urls(
|
||||
client: httpx.AsyncClient,
|
||||
urls: list[str],
|
||||
) -> tuple[list[str], list[str]]:
|
||||
failures: list[str] = []
|
||||
for url in urls:
|
||||
endpoint = url.split("?")[0]
|
||||
try:
|
||||
response = await client.get(url)
|
||||
except httpx.HTTPError as exc:
|
||||
failures.append(f"{endpoint}: network error ({type(exc).__name__}: {exc})")
|
||||
continue
|
||||
|
||||
if response.status_code != 200:
|
||||
failures.append(f"{endpoint}: HTTP {response.status_code}")
|
||||
continue
|
||||
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
failures.append(f"{endpoint}: invalid JSON payload")
|
||||
continue
|
||||
|
||||
symbols = _extract_symbols_from_fmp_payload(payload)
|
||||
if symbols:
|
||||
return symbols, failures
|
||||
|
||||
failures.append(f"{endpoint}: empty/unsupported payload")
|
||||
|
||||
return [], failures
|
||||
|
||||
|
||||
async def _fetch_universe_symbols_from_fmp(universe: str) -> list[str]:
|
||||
if not settings.fmp_api_key:
|
||||
raise ValidationError(
|
||||
"FMP API key is required for universe bootstrap (set FMP_API_KEY)"
|
||||
)
|
||||
|
||||
api_key = settings.fmp_api_key
|
||||
stable_base = "https://financialmodelingprep.com/stable"
|
||||
legacy_base = "https://financialmodelingprep.com/api/v3"
|
||||
|
||||
stable_candidates: dict[str, list[str]] = {
|
||||
"sp500": [
|
||||
f"{stable_base}/sp500-constituent?apikey={api_key}",
|
||||
f"{stable_base}/sp500-constituents?apikey={api_key}",
|
||||
],
|
||||
"nasdaq100": [
|
||||
f"{stable_base}/nasdaq-100-constituent?apikey={api_key}",
|
||||
f"{stable_base}/nasdaq100-constituent?apikey={api_key}",
|
||||
f"{stable_base}/nasdaq-100-constituents?apikey={api_key}",
|
||||
],
|
||||
"nasdaq_all": [
|
||||
f"{stable_base}/stock-screener?exchange=NASDAQ&isEtf=false&limit=10000&apikey={api_key}",
|
||||
f"{stable_base}/available-traded/list?apikey={api_key}",
|
||||
],
|
||||
}
|
||||
|
||||
legacy_candidates: dict[str, list[str]] = {
|
||||
"sp500": [
|
||||
f"{legacy_base}/sp500_constituent?apikey={api_key}",
|
||||
f"{legacy_base}/sp500_constituent",
|
||||
],
|
||||
"nasdaq100": [
|
||||
f"{legacy_base}/nasdaq_constituent?apikey={api_key}",
|
||||
f"{legacy_base}/nasdaq_constituent",
|
||||
],
|
||||
"nasdaq_all": [
|
||||
f"{legacy_base}/stock-screener?exchange=NASDAQ&isEtf=false&limit=10000&apikey={api_key}",
|
||||
],
|
||||
}
|
||||
|
||||
failures: list[str] = []
|
||||
async with httpx.AsyncClient(timeout=30.0, verify=_CA_BUNDLE_PATH) as client:
|
||||
stable_symbols, stable_failures = await _try_fmp_urls(client, stable_candidates[universe])
|
||||
failures.extend(stable_failures)
|
||||
|
||||
if stable_symbols:
|
||||
return stable_symbols
|
||||
|
||||
legacy_symbols, legacy_failures = await _try_fmp_urls(client, legacy_candidates[universe])
|
||||
failures.extend(legacy_failures)
|
||||
|
||||
if legacy_symbols:
|
||||
return legacy_symbols
|
||||
|
||||
if failures:
|
||||
reason = "; ".join(failures[:6])
|
||||
logger.warning("FMP universe fetch failed for %s: %s", universe, reason)
|
||||
raise ProviderError(
|
||||
f"Failed to fetch universe symbols from FMP for '{universe}'. Attempts: {reason}"
|
||||
)
|
||||
|
||||
raise ProviderError(f"Failed to fetch universe symbols from FMP for '{universe}'")
|
||||
|
||||
|
||||
async def _fetch_html_symbols(
|
||||
async def _fetch_wiki_constituent_symbols(
|
||||
client: httpx.AsyncClient,
|
||||
url: str,
|
||||
pattern: str,
|
||||
) -> tuple[list[str], str | None]:
|
||||
try:
|
||||
response = await client.get(url)
|
||||
response = await client.get(url, headers=_HTTP_HEADERS)
|
||||
except httpx.HTTPError as exc:
|
||||
return [], f"{url}: network error ({type(exc).__name__}: {exc})"
|
||||
|
||||
if response.status_code != 200:
|
||||
return [], f"{url}: HTTP {response.status_code}"
|
||||
|
||||
matches = re.findall(pattern, response.text, flags=re.IGNORECASE)
|
||||
matches = _extract_wiki_symbols(response.text)
|
||||
if not matches:
|
||||
return [], f"{url}: no symbols parsed"
|
||||
return list(matches), None
|
||||
@@ -210,7 +136,7 @@ async def _fetch_nasdaq_trader_symbols(
|
||||
) -> tuple[list[str], str | None]:
|
||||
url = "https://www.nasdaqtrader.com/dynamic/SymDir/nasdaqlisted.txt"
|
||||
try:
|
||||
response = await client.get(url)
|
||||
response = await client.get(url, headers=_HTTP_HEADERS)
|
||||
except httpx.HTTPError as exc:
|
||||
return [], f"{url}: network error ({type(exc).__name__}: {exc})"
|
||||
|
||||
@@ -240,18 +166,17 @@ async def _fetch_universe_symbols_from_public(universe: str) -> tuple[list[str],
|
||||
|
||||
sp500_url = "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
|
||||
nasdaq100_url = "https://en.wikipedia.org/wiki/Nasdaq-100"
|
||||
wiki_symbol_pattern = r"<td>\s*<a[^>]*>([A-Z.]{1,10})</a>\s*</td>"
|
||||
|
||||
async with httpx.AsyncClient(timeout=30.0, verify=_CA_BUNDLE_PATH) as client:
|
||||
if universe == "sp500":
|
||||
symbols, error = await _fetch_html_symbols(client, sp500_url, wiki_symbol_pattern)
|
||||
symbols, error = await _fetch_wiki_constituent_symbols(client, sp500_url)
|
||||
if error:
|
||||
failures.append(error)
|
||||
else:
|
||||
return symbols, failures, "wikipedia_sp500"
|
||||
|
||||
if universe == "nasdaq100":
|
||||
symbols, error = await _fetch_html_symbols(client, nasdaq100_url, wiki_symbol_pattern)
|
||||
symbols, error = await _fetch_wiki_constituent_symbols(client, nasdaq100_url)
|
||||
if error:
|
||||
failures.append(error)
|
||||
else:
|
||||
@@ -308,14 +233,24 @@ async def _write_cached_symbols(
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def fetch_universe_symbols(db: AsyncSession, universe: str) -> list[str]:
|
||||
async def fetch_universe_symbols(
|
||||
db: AsyncSession,
|
||||
universe: str,
|
||||
) -> tuple[list[str], str]:
|
||||
"""Fetch and normalise symbols for a supported universe with fallbacks.
|
||||
|
||||
Fallback order:
|
||||
1) Free public sources (Wikipedia/NASDAQ trader)
|
||||
2) FMP endpoints (if available)
|
||||
3) Cached snapshot in SystemSetting
|
||||
4) Built-in seed symbols
|
||||
2) Cached snapshot in SystemSetting
|
||||
3) Built-in seed symbols
|
||||
|
||||
Returns ``(symbols, source_label)`` so bootstrap UI can show where the
|
||||
list came from (important when the public source fails and a stale cache
|
||||
still lists BK instead of BNY).
|
||||
|
||||
The seeds are representative, not complete, so a *fresh* install whose
|
||||
public source is down bootstraps a partial universe. A warm instance is
|
||||
unaffected — it falls through to its cached snapshot.
|
||||
"""
|
||||
normalised_universe = _validate_universe(universe)
|
||||
failures: list[str] = []
|
||||
@@ -325,16 +260,7 @@ async def fetch_universe_symbols(db: AsyncSession, universe: str) -> list[str]:
|
||||
cleaned_public = _normalise_symbols(public_symbols)
|
||||
if cleaned_public:
|
||||
await _write_cached_symbols(db, normalised_universe, cleaned_public, public_source or "public")
|
||||
return cleaned_public
|
||||
|
||||
try:
|
||||
fmp_symbols = await _fetch_universe_symbols_from_fmp(normalised_universe)
|
||||
cleaned_fmp = _normalise_symbols(fmp_symbols)
|
||||
if cleaned_fmp:
|
||||
await _write_cached_symbols(db, normalised_universe, cleaned_fmp, "fmp")
|
||||
return cleaned_fmp
|
||||
except (ProviderError, ValidationError) as exc:
|
||||
failures.append(str(exc))
|
||||
return cleaned_public, public_source or "public"
|
||||
|
||||
cached_symbols = await _read_cached_symbols(db, normalised_universe)
|
||||
if cached_symbols:
|
||||
@@ -343,7 +269,7 @@ async def fetch_universe_symbols(db: AsyncSession, universe: str) -> list[str]:
|
||||
normalised_universe,
|
||||
"; ".join(failures[:3]),
|
||||
)
|
||||
return cached_symbols
|
||||
return cached_symbols, "cache"
|
||||
|
||||
seed_symbols = _normalise_symbols(_SEED_UNIVERSES.get(normalised_universe, []))
|
||||
if seed_symbols:
|
||||
@@ -352,7 +278,7 @@ async def fetch_universe_symbols(db: AsyncSession, universe: str) -> list[str]:
|
||||
normalised_universe,
|
||||
"; ".join(failures[:3]),
|
||||
)
|
||||
return seed_symbols
|
||||
return seed_symbols, "seed"
|
||||
|
||||
reason = "; ".join(failures[:6]) if failures else "no provider returned symbols"
|
||||
raise ProviderError(f"Universe '{normalised_universe}' returned no valid symbols. Attempts: {reason}")
|
||||
@@ -418,7 +344,7 @@ async def bootstrap_universe(
|
||||
Returns summary counts for added/existing/deleted symbols.
|
||||
"""
|
||||
normalised_universe = _validate_universe(universe)
|
||||
symbols = await fetch_universe_symbols(db, normalised_universe)
|
||||
symbols, source = await fetch_universe_symbols(db, normalised_universe)
|
||||
|
||||
existing_rows = await db.execute(select(Ticker.symbol))
|
||||
existing_symbols = set(existing_rows.scalars().all())
|
||||
@@ -431,9 +357,26 @@ async def bootstrap_universe(
|
||||
db.add(Ticker(symbol=symbol))
|
||||
|
||||
deleted_count = 0
|
||||
skipped_delisted: list[str] = []
|
||||
if symbols_to_delete:
|
||||
result = await db.execute(delete(Ticker).where(Ticker.symbol.in_(symbols_to_delete)))
|
||||
deleted_count = int(result.rowcount or 0)
|
||||
# A delisted row was retained on purpose — its price history is exactly
|
||||
# what a survivorship-honest backtest needs, and the delete cascades it
|
||||
# away. Pruning must not undo that. (Pruning a symbol that is merely no
|
||||
# longer an index constituent still destroys history; that needs a
|
||||
# tracked/membership state separate from delisting.)
|
||||
protected = (
|
||||
await db.execute(
|
||||
select(Ticker.symbol).where(
|
||||
Ticker.symbol.in_(symbols_to_delete),
|
||||
Ticker.delisted_on.is_not(None),
|
||||
)
|
||||
)
|
||||
).scalars().all()
|
||||
skipped_delisted = sorted(protected)
|
||||
deletable = [s for s in symbols_to_delete if s not in set(protected)]
|
||||
if deletable:
|
||||
result = await db.execute(delete(Ticker).where(Ticker.symbol.in_(deletable)))
|
||||
deleted_count = int(result.rowcount or 0)
|
||||
|
||||
await db.commit()
|
||||
|
||||
@@ -446,8 +389,14 @@ async def bootstrap_universe(
|
||||
|
||||
return {
|
||||
"universe": normalised_universe,
|
||||
"source": source,
|
||||
"total_universe_symbols": len(symbols),
|
||||
"added": len(symbols_to_add),
|
||||
"already_tracked": len(target_symbols & existing_symbols),
|
||||
"deleted": deleted_count,
|
||||
"added_symbols": symbols_to_add[:50],
|
||||
# Delisted rows a prune declined to destroy, so the caller can see the
|
||||
# count did not match what they asked to remove.
|
||||
"kept_delisted": skipped_delisted[:50],
|
||||
"kept_delisted_count": len(skipped_delisted),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Shared live trading-policy state and availability checks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from datetime import date, datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.paper_trade import PaperTrade
|
||||
|
||||
# Gate-reset "day" boundary matches US cash equities session calendar, not UTC.
|
||||
_REENTRY_DAY_TZ = ZoneInfo("America/New_York")
|
||||
|
||||
|
||||
def _ny_trading_date(moment: datetime) -> date:
|
||||
"""Calendar date in America/New_York for a gate-reset observation."""
|
||||
if moment.tzinfo is None:
|
||||
moment = moment.replace(tzinfo=timezone.utc)
|
||||
return moment.astimezone(_REENTRY_DAY_TZ).date()
|
||||
|
||||
|
||||
MANUAL_BOOK = "manual"
|
||||
SHADOW_BOOK = "shadow"
|
||||
|
||||
|
||||
async def _latest_initial_stop_trades(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
closed_before: datetime | None = None,
|
||||
book: str = MANUAL_BOOK,
|
||||
) -> dict[int, PaperTrade]:
|
||||
"""Return a ticker's latest closed trade only when it was an initial stop.
|
||||
|
||||
Scoped to one ``book``: the discretionary and shadow books diverge as soon
|
||||
as their entries differ, so each must see only its own stop history when
|
||||
deciding whether a ticker is locked out of re-entry.
|
||||
"""
|
||||
ranked_stmt = (
|
||||
select(
|
||||
PaperTrade.id.label("trade_id"),
|
||||
func.row_number()
|
||||
.over(
|
||||
partition_by=PaperTrade.ticker_id,
|
||||
order_by=(PaperTrade.closed_at.desc(), PaperTrade.id.desc()),
|
||||
)
|
||||
.label("recency"),
|
||||
)
|
||||
.where(
|
||||
PaperTrade.status == "closed",
|
||||
PaperTrade.closed_at.is_not(None),
|
||||
PaperTrade.book == book,
|
||||
)
|
||||
)
|
||||
if closed_before is not None:
|
||||
ranked_stmt = ranked_stmt.where(PaperTrade.closed_at <= closed_before)
|
||||
ranked = ranked_stmt.subquery()
|
||||
stmt = (
|
||||
select(PaperTrade)
|
||||
.join(ranked, ranked.c.trade_id == PaperTrade.id)
|
||||
.where(
|
||||
ranked.c.recency == 1,
|
||||
PaperTrade.close_reason == "stop",
|
||||
)
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
return {trade.ticker_id: trade for trade in result.scalars()}
|
||||
|
||||
|
||||
async def get_reentry_gate_locks(
|
||||
db: AsyncSession, *, book: str = MANUAL_BOOK
|
||||
) -> dict[int, datetime]:
|
||||
"""Return tickers still waiting for a post-stop gate failure.
|
||||
|
||||
A later qualified setup is actionable only after the daily scanner has
|
||||
observed an unqualified evaluation after the latest initial-stop exit and
|
||||
then a fresh qualification. The returned timestamp is the stop time and is
|
||||
useful for diagnostics; callers normally only need the keys.
|
||||
"""
|
||||
latest = await _latest_initial_stop_trades(db, book=book)
|
||||
return {
|
||||
ticker_id: trade.closed_at
|
||||
for ticker_id, trade in latest.items()
|
||||
if trade.reentry_gate_requalified_at is None and trade.closed_at is not None
|
||||
}
|
||||
|
||||
|
||||
async def observe_reentry_gate_transitions(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
evaluated_ticker_ids: Iterable[int],
|
||||
qualified_ticker_ids: Iterable[int],
|
||||
observed_at: datetime | None = None,
|
||||
book: str = MANUAL_BOOK,
|
||||
) -> set[int]:
|
||||
"""Persist gate-failure and later requalification observations.
|
||||
|
||||
Only tickers whose scan completed successfully belong in
|
||||
``evaluated_ticker_ids``. This prevents a scanner exception from being
|
||||
mistaken for a real gate exit. The caller owns the transaction; this helper
|
||||
flushes so the new state is immediately visible in that transaction.
|
||||
"""
|
||||
evaluated = {int(ticker_id) for ticker_id in evaluated_ticker_ids}
|
||||
if not evaluated:
|
||||
return set()
|
||||
qualified = {int(ticker_id) for ticker_id in qualified_ticker_ids}
|
||||
timestamp = observed_at or datetime.now(timezone.utc)
|
||||
latest = await _latest_initial_stop_trades(db, closed_before=timestamp, book=book)
|
||||
updated: set[int] = set()
|
||||
for ticker_id in evaluated:
|
||||
trade = latest.get(ticker_id)
|
||||
if trade is None or trade.reentry_gate_requalified_at is not None:
|
||||
continue
|
||||
if trade.reentry_gate_failed_at is None:
|
||||
if ticker_id not in qualified:
|
||||
trade.reentry_gate_failed_at = timestamp
|
||||
updated.add(ticker_id)
|
||||
elif ticker_id in qualified:
|
||||
# Study semantics: requalify only on a *subsequent* daily observation.
|
||||
# Same America/New_York calendar day as the failure does not unlock,
|
||||
# even if multiple full-universe scans run (manual + near-close).
|
||||
if _ny_trading_date(trade.reentry_gate_failed_at) < _ny_trading_date(
|
||||
timestamp
|
||||
):
|
||||
trade.reentry_gate_requalified_at = timestamp
|
||||
updated.add(ticker_id)
|
||||
|
||||
if updated:
|
||||
await db.flush()
|
||||
return updated
|
||||
@@ -103,89 +103,6 @@ async def remove_entry(
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def _enrich_entry(
|
||||
db: AsyncSession,
|
||||
entry: WatchlistEntry,
|
||||
symbol: str,
|
||||
) -> dict:
|
||||
"""Build enriched watchlist entry dict with scores, R:R, SR levels, price."""
|
||||
ticker_id = entry.ticker_id
|
||||
|
||||
# Composite score
|
||||
comp_result = await db.execute(
|
||||
select(CompositeScore).where(CompositeScore.ticker_id == ticker_id)
|
||||
)
|
||||
comp = comp_result.scalar_one_or_none()
|
||||
|
||||
# Dimension scores
|
||||
dim_result = await db.execute(
|
||||
select(DimensionScore).where(DimensionScore.ticker_id == ticker_id)
|
||||
)
|
||||
dims = [
|
||||
{"dimension": ds.dimension, "score": ds.score}
|
||||
for ds in dim_result.scalars().all()
|
||||
]
|
||||
|
||||
# Best trade setup (highest R:R) for this ticker
|
||||
setup_result = await db.execute(
|
||||
select(TradeSetup)
|
||||
.where(TradeSetup.ticker_id == ticker_id)
|
||||
.order_by(TradeSetup.rr_ratio.desc())
|
||||
.limit(1)
|
||||
)
|
||||
setup = setup_result.scalar_one_or_none()
|
||||
|
||||
# Active SR levels
|
||||
sr_result = await db.execute(
|
||||
select(SRLevel)
|
||||
.where(SRLevel.ticker_id == ticker_id)
|
||||
.order_by(SRLevel.strength.desc())
|
||||
)
|
||||
sr_levels = [
|
||||
{
|
||||
"price_level": lv.price_level,
|
||||
"type": lv.type,
|
||||
"strength": lv.strength,
|
||||
}
|
||||
for lv in sr_result.scalars().all()
|
||||
]
|
||||
|
||||
# Latest two daily closes → current price + day-over-day move
|
||||
price_result = await db.execute(
|
||||
select(OHLCVRecord.close, OHLCVRecord.date)
|
||||
.where(OHLCVRecord.ticker_id == ticker_id)
|
||||
.order_by(OHLCVRecord.date.desc())
|
||||
.limit(2)
|
||||
)
|
||||
bars = price_result.all()
|
||||
last_close = bars[0].close if bars else None
|
||||
prev_close = bars[1].close if len(bars) > 1 else None
|
||||
change_pct = (
|
||||
(last_close - prev_close) / prev_close * 100
|
||||
if last_close is not None and prev_close
|
||||
else None
|
||||
)
|
||||
price_date = bars[0].date if bars else None
|
||||
|
||||
return {
|
||||
"symbol": symbol,
|
||||
"entry_type": entry.entry_type,
|
||||
"composite_score": comp.score if comp else None,
|
||||
"dimensions": dims,
|
||||
"rr_ratio": setup.rr_ratio if setup else None,
|
||||
"rr_direction": setup.direction if setup else None,
|
||||
# Residual 12-1 activation percentile gates qualification; strategy_rank
|
||||
# is the promoted top-pick ordering score.
|
||||
"momentum_percentile": setup.momentum_percentile if setup else None,
|
||||
"strategy_rank": setup.strategy_rank if setup else None,
|
||||
"sr_levels": sr_levels,
|
||||
"last_close": last_close,
|
||||
"change_pct": change_pct,
|
||||
"price_date": price_date,
|
||||
"added_at": entry.added_at,
|
||||
}
|
||||
|
||||
|
||||
async def _enrich_entries(
|
||||
db: AsyncSession,
|
||||
rows: list[tuple[WatchlistEntry, str]],
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""TLS / corporate-proxy bootstrap for CLI scripts and the API.
|
||||
|
||||
Must run **before** httpx / alpaca / aiohttp open connections.
|
||||
|
||||
Resolution order for the CA bundle:
|
||||
1. ``combined-ca-bundle.pem`` in the repo root (gitignored corporate bundle)
|
||||
2. ``$HOME/combined-ca-bundle.pem`` (MacBook path used by existing tooling)
|
||||
3. ``SSL_CERT_FILE`` / ``REQUESTS_CA_BUNDLE`` if already set and present
|
||||
4. ``certifi.where()`` when the package is installed
|
||||
5. System defaults (no patch)
|
||||
|
||||
Optional corporate proxy (Swisscom-style) when ``USE_CORP_PROXY=1``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
|
||||
_BOOTSTRAPPED = False
|
||||
|
||||
|
||||
def _candidate_ca_paths() -> list[Path]:
|
||||
root = Path(__file__).resolve().parent.parent
|
||||
home = Path.home()
|
||||
env_paths = [
|
||||
os.environ.get("SSL_CERT_FILE", ""),
|
||||
os.environ.get("REQUESTS_CA_BUNDLE", ""),
|
||||
os.environ.get("CURL_CA_BUNDLE", ""),
|
||||
]
|
||||
paths = [
|
||||
root / "combined-ca-bundle.pem",
|
||||
home / "combined-ca-bundle.pem",
|
||||
*[Path(p) for p in env_paths if p],
|
||||
]
|
||||
try:
|
||||
import certifi
|
||||
|
||||
paths.append(Path(certifi.where()))
|
||||
except Exception:
|
||||
pass
|
||||
return paths
|
||||
|
||||
|
||||
def resolve_ca_bundle() -> str | None:
|
||||
for path in _candidate_ca_paths():
|
||||
try:
|
||||
if path.is_file() and path.stat().st_size > 0:
|
||||
return str(path.resolve())
|
||||
except OSError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def apply_corp_proxy_if_requested() -> None:
|
||||
if os.environ.get("USE_CORP_PROXY", "0") != "1":
|
||||
return
|
||||
proxy = os.environ.get("CORP_HTTP_PROXY", "http://aproxy.corproot.net:8080")
|
||||
no_proxy = os.environ.get(
|
||||
"CORP_NO_PROXY",
|
||||
"corproot.net,sharedtcs.net,127.0.0.1,localhost,bix.swisscom.com,swisscom.com",
|
||||
)
|
||||
os.environ.setdefault("HTTP_PROXY", proxy)
|
||||
os.environ.setdefault("HTTPS_PROXY", proxy)
|
||||
os.environ.setdefault("NO_PROXY", no_proxy)
|
||||
os.environ.setdefault("http_proxy", proxy)
|
||||
os.environ.setdefault("https_proxy", proxy)
|
||||
os.environ.setdefault("no_proxy", no_proxy)
|
||||
|
||||
|
||||
def bootstrap_ssl(*, force: bool = False) -> str | None:
|
||||
"""Install CA env vars + patch ``ssl.create_default_context``.
|
||||
|
||||
Returns the CA path used, or None if nothing was applied.
|
||||
Safe to call multiple times.
|
||||
"""
|
||||
global _BOOTSTRAPPED
|
||||
if _BOOTSTRAPPED and not force:
|
||||
return os.environ.get("SSL_CERT_FILE") or None
|
||||
|
||||
apply_corp_proxy_if_requested()
|
||||
|
||||
cert_path = resolve_ca_bundle()
|
||||
if not cert_path:
|
||||
_BOOTSTRAPPED = True
|
||||
return None
|
||||
|
||||
os.environ["SSL_CERT_FILE"] = cert_path
|
||||
os.environ["REQUESTS_CA_BUNDLE"] = cert_path
|
||||
os.environ["CURL_CA_BUNDLE"] = cert_path
|
||||
|
||||
original = ssl.create_default_context
|
||||
|
||||
def _patched(
|
||||
purpose=ssl.Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None
|
||||
):
|
||||
ctx = original(purpose, cafile=cafile, capath=capath, cadata=cadata)
|
||||
try:
|
||||
ctx.load_verify_locations(cafile=cert_path)
|
||||
except Exception:
|
||||
pass
|
||||
return ctx
|
||||
|
||||
ssl.create_default_context = _patched # type: ignore[assignment]
|
||||
|
||||
# aiohttp may cache SSL contexts at import time.
|
||||
try:
|
||||
import aiohttp.connector as aio_conn
|
||||
|
||||
for attr in ("_SSL_CONTEXT_VERIFIED", "_SSL_CONTEXT_UNVERIFIED"):
|
||||
ctx = getattr(aio_conn, attr, None)
|
||||
if ctx is not None:
|
||||
try:
|
||||
ctx.load_verify_locations(cafile=cert_path)
|
||||
except Exception:
|
||||
pass
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
_BOOTSTRAPPED = True
|
||||
return cert_path
|
||||
|
||||
|
||||
def ssl_status() -> dict:
|
||||
"""Diagnostic blob for research scripts / MacBook troubleshooting."""
|
||||
ca = resolve_ca_bundle()
|
||||
return {
|
||||
"ca_bundle": ca,
|
||||
"ssl_cert_file_env": os.environ.get("SSL_CERT_FILE"),
|
||||
"use_corp_proxy": os.environ.get("USE_CORP_PROXY", "0"),
|
||||
"http_proxy": os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY"),
|
||||
"candidates_exist": {
|
||||
str(p): p.is_file() for p in _candidate_ca_paths()[:4]
|
||||
},
|
||||
}
|
||||
Executable
+140
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# One-time production provisioning for the shadow fundamentals sources.
|
||||
# Run as root to install; run with --check as the deploy user for a read-only
|
||||
# preflight. Version upgrades are intentional code changes, never "latest".
|
||||
DOLT_VERSION="2.2.0"
|
||||
DOLT_BINARY="${DOLT_BINARY:-/usr/local/bin/dolt}"
|
||||
DOLT_DATA_DIR="${DOLT_DATA_DIR:-/var/lib/signal-platform/dolt}"
|
||||
DOLT_EARNINGS_SUBDIR="${DOLT_EARNINGS_SUBDIR:-earnings}"
|
||||
APP_USER="${APP_USER:-deploy}"
|
||||
APP_GROUP="${APP_GROUP:-deploy}"
|
||||
ENV_FILE="${ENV_FILE:-/opt/signalplatform/.env}"
|
||||
MIN_FREE_GB="${DOLT_MIN_FREE_DISK_GB:-5}"
|
||||
EARNINGS_DIR="${DOLT_DATA_DIR}/${DOLT_EARNINGS_SUBDIR}"
|
||||
DOLT_IDENTITY_NAME="${DOLT_IDENTITY_NAME:-Signal Platform}"
|
||||
DOLT_IDENTITY_EMAIL="${DOLT_IDENTITY_EMAIL:-signal-platform@localhost}"
|
||||
|
||||
fail() {
|
||||
echo "ERROR: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
version_ok() {
|
||||
local output
|
||||
output="$("$DOLT_BINARY" version 2>/dev/null || true)"
|
||||
grep -Eq "(^|[[:space:]])v?${DOLT_VERSION}([[:space:]]|$)" <<<"$output"
|
||||
}
|
||||
|
||||
as_app_user() {
|
||||
if [[ "$(id -un)" == "$APP_USER" ]]; then
|
||||
"$@"
|
||||
else
|
||||
command -v runuser >/dev/null 2>&1 || fail "runuser is required"
|
||||
runuser -u "$APP_USER" -- "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
repo_command() {
|
||||
(
|
||||
cd "$EARNINGS_DIR"
|
||||
as_app_user "$@"
|
||||
)
|
||||
}
|
||||
|
||||
repo_config_value() {
|
||||
repo_command "$DOLT_BINARY" config --get "$1"
|
||||
}
|
||||
|
||||
configure_identity() {
|
||||
local name email
|
||||
name="$(repo_config_value user.name 2>/dev/null || true)"
|
||||
email="$(repo_config_value user.email 2>/dev/null || true)"
|
||||
if [[ -z "$name" ]]; then
|
||||
repo_command "$DOLT_BINARY" config --local --add user.name "$DOLT_IDENTITY_NAME"
|
||||
fi
|
||||
if [[ -z "$email" ]]; then
|
||||
repo_command "$DOLT_BINARY" config --local --add user.email "$DOLT_IDENTITY_EMAIL"
|
||||
fi
|
||||
}
|
||||
|
||||
check_free_space() {
|
||||
local available_kb
|
||||
available_kb="$(df -Pk "$DOLT_DATA_DIR" | awk 'NR == 2 {print $4}')"
|
||||
[[ "$available_kb" =~ ^[0-9]+$ ]] || fail "could not read free space for $DOLT_DATA_DIR"
|
||||
if ! awk -v available="$available_kb" -v minimum_gb="$MIN_FREE_GB" \
|
||||
'BEGIN { exit !(available >= minimum_gb * 1024 * 1024) }'; then
|
||||
fail "$DOLT_DATA_DIR has less than ${MIN_FREE_GB} GB free"
|
||||
fi
|
||||
}
|
||||
|
||||
check_env() {
|
||||
[[ -f "$ENV_FILE" ]] || fail "missing environment file: $ENV_FILE"
|
||||
grep -Fqx "DOLT_BINARY=$DOLT_BINARY" "$ENV_FILE" \
|
||||
|| fail "set DOLT_BINARY=$DOLT_BINARY in $ENV_FILE"
|
||||
grep -Fqx "DOLT_DATA_DIR=$DOLT_DATA_DIR" "$ENV_FILE" \
|
||||
|| fail "set DOLT_DATA_DIR=$DOLT_DATA_DIR in $ENV_FILE"
|
||||
grep -Fqx "DOLT_EARNINGS_SUBDIR=$DOLT_EARNINGS_SUBDIR" "$ENV_FILE" \
|
||||
|| fail "set DOLT_EARNINGS_SUBDIR=$DOLT_EARNINGS_SUBDIR in $ENV_FILE"
|
||||
grep -Eq '^SEC_USER_AGENT=.*@.*' "$ENV_FILE" \
|
||||
|| fail "SEC_USER_AGENT in $ENV_FILE must contain a real contact email"
|
||||
}
|
||||
|
||||
check_all() {
|
||||
local identity_name identity_email
|
||||
id "$APP_USER" >/dev/null 2>&1 || fail "missing service user: $APP_USER"
|
||||
[[ -x "$DOLT_BINARY" ]] || fail "missing Dolt binary: $DOLT_BINARY"
|
||||
version_ok || fail "expected Dolt $DOLT_VERSION at $DOLT_BINARY"
|
||||
[[ -d "$EARNINGS_DIR/.dolt" ]] \
|
||||
|| fail "missing earnings clone: $EARNINGS_DIR"
|
||||
if [[ "$(id -un)" == "$APP_USER" ]]; then
|
||||
[[ -r "$EARNINGS_DIR/.dolt" ]] \
|
||||
|| fail "earnings clone is not readable by $APP_USER"
|
||||
elif command -v runuser >/dev/null 2>&1; then
|
||||
runuser -u "$APP_USER" -- test -r "$EARNINGS_DIR/.dolt" \
|
||||
|| fail "earnings clone is not readable by $APP_USER"
|
||||
else
|
||||
fail "run --check as $APP_USER (or install runuser)"
|
||||
fi
|
||||
identity_name="$(repo_config_value user.name 2>/dev/null || true)"
|
||||
identity_email="$(repo_config_value user.email 2>/dev/null || true)"
|
||||
[[ -n "$identity_name" ]] || fail "missing Dolt user.name for $EARNINGS_DIR"
|
||||
[[ -n "$identity_email" ]] || fail "missing Dolt user.email for $EARNINGS_DIR"
|
||||
check_free_space
|
||||
check_env
|
||||
echo "OK: Dolt $DOLT_VERSION and earnings clone are provisioned"
|
||||
}
|
||||
|
||||
if [[ "${1:-}" == "--check" ]]; then
|
||||
check_all
|
||||
exit 0
|
||||
fi
|
||||
|
||||
[[ "$EUID" -eq 0 ]] || fail "run provisioning as root (or use --check)"
|
||||
command -v curl >/dev/null 2>&1 || fail "curl is required"
|
||||
command -v runuser >/dev/null 2>&1 || fail "runuser is required"
|
||||
id "$APP_USER" >/dev/null 2>&1 || fail "missing service user: $APP_USER"
|
||||
|
||||
if ! version_ok; then
|
||||
installer="$(mktemp)"
|
||||
trap 'rm -f "$installer"' EXIT
|
||||
curl -fsSL \
|
||||
"https://github.com/dolthub/dolt/releases/download/v${DOLT_VERSION}/install.sh" \
|
||||
-o "$installer"
|
||||
bash "$installer"
|
||||
fi
|
||||
version_ok || fail "Dolt $DOLT_VERSION installation failed"
|
||||
|
||||
install -d -o "$APP_USER" -g "$APP_GROUP" -m 0750 "$DOLT_DATA_DIR"
|
||||
check_free_space
|
||||
|
||||
if [[ ! -d "$EARNINGS_DIR/.dolt" ]]; then
|
||||
[[ ! -e "$EARNINGS_DIR" ]] \
|
||||
|| fail "$EARNINGS_DIR exists but is not a Dolt clone"
|
||||
runuser -u "$APP_USER" -- \
|
||||
"$DOLT_BINARY" clone post-no-preference/earnings "$EARNINGS_DIR"
|
||||
fi
|
||||
|
||||
configure_identity
|
||||
check_all
|
||||
@@ -0,0 +1,587 @@
|
||||
# Dolt bulk-data integration — implementation plan
|
||||
|
||||
Status: **workstream A complete and deployed** (A0–A6, last step 2026-08-07);
|
||||
**workstream B dropped 2026-08-07** — see § Why B was dropped. Approved 2026-07-21,
|
||||
revised through five review rounds; direction: KISS backend, UI value first.
|
||||
Originally a hand-off document for the implementing agent; now the design record.
|
||||
Current operations live in `docs/fundamentals-deployment.md`.
|
||||
|
||||
## Objective
|
||||
|
||||
Replace the free-tier fundamentals APIs (FMP, Finnhub, Alpha Vantage) with bulk
|
||||
data: SEC Company Facts for fundamentals and the DoltHub earnings repo for the
|
||||
earnings calendar/history. PostgreSQL stays the production system of record.
|
||||
(A third source — the DoltHub stocks repo for historical OHLCV — was planned as
|
||||
workstream B and dropped; Alpaca remains the price source.)
|
||||
|
||||
**Delivery order: two independent workstreams.**
|
||||
|
||||
- **Workstream A (build first):** SEC fundamentals + Dolt earnings + API v1 +
|
||||
FundamentalsPanel + decommission FMP/Finnhub/Alpha Vantage. Valuation uses the
|
||||
existing Alpaca closes already in `ohlcv_records`. This alone achieves the goal
|
||||
(killing the quota-limited APIs) and delivers all the UI value.
|
||||
- **Workstream B — DROPPED 2026-08-07, see below.** Would have replaced historical
|
||||
OHLCV with the Dolt stocks repo. Its design is retained further down as a record,
|
||||
not as a backlog item.
|
||||
|
||||
**Guiding principle: KISS.** Plain daily importers with staging and atomic
|
||||
promotion — no forensic replay, no permanent archive store, no conflict tables, no
|
||||
aggregate tables. Engineering budget goes into the UI (quarter trends, peer
|
||||
comparison). Deferred until a concrete need: exact source replay, point-in-time
|
||||
backtest enforcement, fundamental metrics in scoring.
|
||||
|
||||
**Non-negotiables**
|
||||
|
||||
- The application never queries Dolt/DoltHub or SEC at request time. All access is
|
||||
batch import → PostgreSQL. If a sync fails or the source is unchanged, production
|
||||
continues on the last successfully imported data.
|
||||
- Do not replace PostgreSQL with Dolt/Doltgres. Never commit to the upstream clones.
|
||||
- No owned SEC Dolt repo: SEC JSON is normalized straight into PostgreSQL.
|
||||
- Scoring **code** is unchanged, but swapping the data source changes production
|
||||
behavior: `app/services/scoring_service.py` (~line 450) scores pe_ratio /
|
||||
revenue_growth / earnings_surprise from `fundamental_data`, so new definitions
|
||||
change rankings even with identical code. Cutover of `fundamental_data`
|
||||
population requires the **score-parity gate** (phase A5) — never silently. All
|
||||
*new* metrics are display-only.
|
||||
- Intraday (10:00–15:00), near-close (15:30) and after-close (16:45) pipelines stay
|
||||
on Alpaca unchanged.
|
||||
|
||||
## Data sources
|
||||
|
||||
1. **SEC Company Facts + submissions bulk files** (free, no key; costs bandwidth,
|
||||
CPU and disk — optimize accordingly) — XBRL facts per **issuer (CIK), not per
|
||||
ticker**. Tickers resolve to a CIK via SEC `company_tickers.json` (multi-class
|
||||
issuers like GOOGL/GOOG share one CIK and one set of fundamentals). Submissions
|
||||
also supply the SIC code (peer grouping) and `acceptanceDateTime`. Handle unit
|
||||
variants and fiscal-period alignment (derive Q4 = FY − Q1..Q3 where needed).
|
||||
**Amendments:** retain every accession immutably; readers select the newest
|
||||
valid `accepted_at` snapshot per reporting period at read time. No flags, no
|
||||
mutation.
|
||||
2. **`post-no-preference/earnings`** (DoltHub) — announcement date, BMO/AMC session
|
||||
(partial), period end, EPS estimate/actual, surprise history. Small clone.
|
||||
`scripts/import_dolthub_earnings.py` is a research/SQLite importer — reuse its
|
||||
normalization/alignment logic (calendar↔EPS-history monotonic alignment, SUE
|
||||
scaling) but write a production PostgreSQL importer; do not extend the script.
|
||||
3. **`post-no-preference/stocks`** (DoltHub, **workstream B**) — daily raw OHLCV
|
||||
(unadjusted), symbol metadata, splits, dividends. Publishes ~01:30 ET the
|
||||
following calendar day. Clone is ~4.7 GB.
|
||||
|
||||
**Licensing (phase A0) — DECIDED 2026-07-22:** `post-no-preference/earnings` is
|
||||
**approved for private/internal ingestion under CC BY-SA 4.0**. Conditions the A2
|
||||
importer must honor: preserve the upstream license, attribution, and transformation
|
||||
notes (retain a CC BY-SA 4.0 reference + attribution to `post-no-preference/earnings`
|
||||
and a note of the transformations applied — e.g. in a repo `NOTICE`/attribution file
|
||||
and the importer module); **no public API, bulk export, or redistribution** of the
|
||||
data; re-review licensing before any public or commercial access. The
|
||||
`post-no-preference/stocks` repo (workstream B) is **not** covered here. B was
|
||||
dropped before any licensing review, so that repo has never been assessed — any
|
||||
future use of it starts that review from scratch.
|
||||
|
||||
## Schema
|
||||
|
||||
**Migration 026 (workstream A)** — current head: `025_trade_setup_scan_run_id`:
|
||||
|
||||
- `data_import_runs` — lean: id, source (`sec_facts` | `dolt_earnings` |
|
||||
`dolt_stocks`), revision (Dolt commit hash, or SEC archive SHA-256), status
|
||||
(`running`/`validated`/`promoted`/`no_op`/`failed`), source_max_date, row_counts
|
||||
JSON, validation JSON (includes reconciliation/discrepancy summaries — no
|
||||
separate conflicts table; details go to structured logs), started_at,
|
||||
completed_at, error_details. One run per source at a time (Postgres advisory
|
||||
lock keyed by source).
|
||||
- `earnings_events` — ticker_id, announce_date, session (`bmo`/`amc`/`unknown`),
|
||||
period_end, eps_estimate, eps_actual, source, import_run_id. Unique
|
||||
(ticker_id, announce_date). **Rescheduling:** within each promotion transaction,
|
||||
delete this source's future-dated rows (announce_date > today) and re-insert
|
||||
from the new snapshot, so moved or cancelled dates never linger. Past rows
|
||||
(results) are never deleted.
|
||||
- `tickers` — add nullable `cik`, `sic`, `sic_description` (from SEC submissions /
|
||||
`company_tickers.json`; refreshed by the SEC import; multi-class tickers share
|
||||
values). The only ticker↔issuer join point.
|
||||
- `fundamental_snapshots` — **CIK-keyed, one immutable row per accession**: cik,
|
||||
accession (unique), form, filed_date, **accepted_at** (kept although PIT
|
||||
enforcement is deferred — one timestamp now vs painful retrofit later),
|
||||
**period_start, period_end, fiscal_year, fiscal_period** (the filing's own
|
||||
`dei`/`us-gaap` period identity — required to align non-calendar fiscal years and
|
||||
to derive discrete quarters from cumulative facts), and the **price-independent
|
||||
raw facts** so metrics are recomputable. **Store facts as the filing reports
|
||||
them, not as derived quarters:** duration facts (revenue, net income, diluted EPS,
|
||||
CFO, capex, EBITDA inputs) retain the filing's normalized **cumulative YTD/FY**
|
||||
value for the (period_start → period_end) span; balance-sheet facts (cash+ST
|
||||
investments, total debt, shares outstanding) are **period-end** values.
|
||||
``shares_outstanding`` is a point-in-time count
|
||||
(``dei:EntityCommonStockSharesOutstanding``), not the weighted-average diluted
|
||||
share count — both consumers (est. market cap, YoY dilution) want a
|
||||
point-in-time value. **Nothing
|
||||
derived is frozen into a row:** discrete quarters (10-Q YTD deltas, Q4 = FY −
|
||||
Q1..Q3), TTM, YoY and the four-period metric histories are all computed **at read time** by
|
||||
picking the newest valid accepted_at snapshot for *each* required period — so
|
||||
non-calendar fiscal years resolve correctly and a later amendment to a prior
|
||||
quarter is reflected automatically without ever storing a stale derived quarter.
|
||||
Readers pick the newest valid accepted_at per period; history powers the UI
|
||||
reference comparisons and deterministic reads.
|
||||
- Keep `fundamental_data` (`app/models/fundamental.py`) as the latest-value compat
|
||||
cache, repopulated by the daily SEC job — but only after the phase-A5 parity
|
||||
gate.
|
||||
|
||||
**Migration 027 (workstream B — NEVER WRITTEN; B was dropped, and `027` was
|
||||
subsequently used for `fundamental_snapshots.weighted_avg_diluted_shares`). The
|
||||
design below is a record only:**
|
||||
|
||||
- `ohlcv_source_bars` — source-truth bar table, required because `ohlcv_records`
|
||||
allows one row per (ticker_id, date) (`app/models/ohlcv.py:12`) and Alpaca
|
||||
ingestion upserts it in place (`app/services/price_service.py:82`) — Dolt and
|
||||
Alpaca bars cannot coexist there. Holds **Dolt raw (unadjusted) bars only** —
|
||||
Alpaca bars are already split-adjusted at the provider (`app/providers/alpaca.py:77`
|
||||
requests `Adjustment.SPLIT`) and live exclusively in `ohlcv_records`. Columns:
|
||||
source (`dolt`), adjustment (`raw` — explicit), ticker_id, date, OHLCV,
|
||||
import_run_id; unique (source, ticker_id, date). Changed bars are counted in the
|
||||
run's validation JSON and logged before overwrite.
|
||||
- `corporate_actions` — ticker_id, type (`split`/`dividend`), ex_date,
|
||||
ratio/amount, source, import_run_id. Unique (ticker_id, type, ex_date).
|
||||
- `ohlcv_records` — add nullable `import_run_id` FK and `source` text (default
|
||||
`'alpaca'`).
|
||||
|
||||
## Import framework
|
||||
|
||||
Every importer: idempotent per revision (same Dolt commit / archive checksum →
|
||||
`no_op`, zero row changes); stage into a representation outside the live tables
|
||||
first (in-memory for the small workstream-A sources; a file/table handle is fine
|
||||
if workstream B ever needs it); promotion in one transaction;
|
||||
safe to retry; a failed or unchanged run leaves the current dataset untouched.
|
||||
Record every attempt in `data_import_runs`.
|
||||
|
||||
**SEC access requirements (operational safeguards, per SEC fair-access policy):**
|
||||
send an identifying `User-Agent` with a contact email on every request; stay far
|
||||
below the 10 req/s limit (the bulk endpoints need only a handful of requests per
|
||||
run); exponential backoff on 429; a 403 means the User-Agent or request pattern is
|
||||
wrong — alert and stop, never retry-loop. See SEC developer resources
|
||||
(https://www.sec.gov/about/developer-resources).
|
||||
|
||||
**Reproducibility scope (deliberately limited):** the normalized snapshots in
|
||||
PostgreSQL *are* the durable record. Keep only the last ~2 SEC archives on disk for
|
||||
debugging. Byte-level replay of old runs is out of scope until a concrete need.
|
||||
|
||||
Dolt access: `dolt pull` on the persistent clone, record the resulting commit hash,
|
||||
read via `dolt sql -r csv` (no long-running sql-server). **The scheduler shares one
|
||||
event loop with the API** (`app/scheduler.py:73`) — run dolt/unzip/download
|
||||
subprocesses via `asyncio.create_subprocess_exec` (or an executor), never blocking
|
||||
calls. Check free disk space before pulling; alert and skip if below threshold.
|
||||
|
||||
**Deployment constraints:** deploy is `rsync --delete` of the repo tree
|
||||
(`.gitea/workflows/deploy.yml:127`), so clones and archives must live **outside the
|
||||
deployment path** — an env-configured persistent directory (e.g.
|
||||
`DOLT_DATA_DIR=/var/lib/signal-platform/dolt`). The dolt binary is a new prod
|
||||
runtime dependency: install it once with the version-pinned provisioner in
|
||||
`deploy/provision_fundamentals.sh`; operational steps are in
|
||||
`docs/fundamentals-deployment.md`. The clone is reproducible from DoltHub; the
|
||||
normalized PostgreSQL rows remain part of the normal database backup.
|
||||
|
||||
**Validation gates (block promotion, raise an alert via the existing system-events
|
||||
path):** source freshness as expected; tracked-universe coverage; no duplicate
|
||||
business keys; fundamental units/periods consistent; row-count deltas within
|
||||
reason; upstream schema change stops promotion. Workstream B adds: OHLC sanity
|
||||
(high ≥ open/close/low, low ≤ open/close/high, volume ≥ 0); no unexplained split
|
||||
discontinuities.
|
||||
|
||||
**Split adjustment (workstream B):** `ohlcv_source_bars` + `corporate_actions` are
|
||||
the source of truth; canonical `ohlcv_records` is *generated* from them to match
|
||||
Alpaca `Adjustment.SPLIT`, selecting only adjustment = `raw` rows as input so
|
||||
adjustment is applied exactly once. A newly published split rewrites the symbol's
|
||||
entire adjusted history — treat whole-symbol rewrites as a normal import event
|
||||
(exempt that symbol from the row-count-delta gate for that run) and stamp rows with
|
||||
the import_run_id (a backtest↔prod parity guard exists; changed history changes
|
||||
backtests).
|
||||
|
||||
## Scheduling (`app/scheduler.py` — `SCHEDULE_DEFAULTS` / `_CRON_JOBS`, ~line 1451)
|
||||
|
||||
Follow the existing pattern: cron strings in SystemSettings via
|
||||
`app/services/settings_store.py`, day-of-week as names never numbers, logging via
|
||||
`_log_event`.
|
||||
|
||||
Workstream A:
|
||||
|
||||
- Dolt earnings import: daily ~02:30 ET (with the future-row replacement above).
|
||||
- **SEC fundamentals job: daily ~04:00 ET.** One job, three steps:
|
||||
(a) detect a composite revision from the latest EDGAR daily-index date, the
|
||||
exact tracked index rows, and the tracked-universe fingerprint — an unchanged
|
||||
revision is a `no_op` before Company Facts are fetched;
|
||||
(b) when changed, fetch and parse Company Facts only for tracked-universe CIKs
|
||||
that filed, plus full available history for the first run or a newly added
|
||||
issuer, through validation→atomic promotion. Universe resolution and the exact
|
||||
index inputs are cached during revision detection and reused during staging;
|
||||
CIKs are resolved from `company_tickers.json` without writes until promotion;
|
||||
(c) **always, locally, and only after production activation** (the phase-A5
|
||||
parity approval): refresh the legacy `fundamental_data` fields and mark affected
|
||||
cached fundamental scores stale. **Sources differ per field** — do not assume all
|
||||
five come from SEC: `pe_ratio` and `market_cap` from the newest valid snapshots ×
|
||||
latest PostgreSQL close, each with its own formula — `pe_ratio` = latest close /
|
||||
TTM diluted EPS; `market_cap` = issuer-wide shares outstanding × latest close;
|
||||
`revenue_growth` from the snapshots alone; `earnings_surprise` and
|
||||
`next_earnings_date` from `earnings_events` (the Dolt earnings feed — these two do
|
||||
not exist in SEC facts). Before activation the job imports snapshots only
|
||||
(shadow). Step (c) must run identically when SEC is unreachable — prices move
|
||||
daily even when filings don't, and the earnings-derived fields already live in
|
||||
PostgreSQL.
|
||||
**The new API valuation object is not stored anywhere** — it is computed at
|
||||
request time (below). No valuation cache or table exists.
|
||||
|
||||
Workstream B (dropped — never built):
|
||||
|
||||
- Dolt OHLCV+splits pull/import: `0 2 * * tue-sat` ET. If source_max_date is not
|
||||
fresh, retry hourly until ~06:00, then give up quietly. After a successful
|
||||
import, reconcile the previous session's Dolt-derived bars against the Alpaca
|
||||
bars; summary into the run's validation JSON, details to logs.
|
||||
- Move `schedule_daily_pipeline_cron` (morning refresh) from `0 2 * * *` to
|
||||
`0 3 * * *` (only needed once the 02:00 slot is taken by the OHLCV pull).
|
||||
**Late Dolt publication is a non-event:** the canonical scan runs at 15:30 on
|
||||
Alpaca, so the morning pipeline runs normally even when the import hasn't
|
||||
landed — no gating, no defensive coupling.
|
||||
|
||||
## Metrics catalog (curated — TTM basis)
|
||||
|
||||
Snapshots store **price-independent per-period facts** (the "snapshot" column below
|
||||
means *derived from stored snapshots, assembled across periods at read time* — see
|
||||
Schema — not frozen at import); price-dependent ratios are never frozen into
|
||||
snapshots and have **no storage location at all**: the API computes
|
||||
them at request time from the stored snapshots + the latest `ohlcv_records` close
|
||||
(both already in PostgreSQL, so this works identically when SEC is unreachable).
|
||||
The only stored price-dependent values are the legacy `fundamental_data` fields
|
||||
that scoring already reads, refreshed daily by step (c) after activation.
|
||||
|
||||
| Metric | Definition | Where computed |
|
||||
|---|---|---|
|
||||
| Revenue growth YoY | TTM revenue vs prior TTM | snapshot |
|
||||
| EPS growth YoY | TTM diluted EPS vs prior TTM | snapshot |
|
||||
| Operating margin + 4q trend | TTM operating income / revenue | snapshot |
|
||||
| FCF margin | (TTM CFO − capex) / revenue | snapshot |
|
||||
| Net debt | total debt − (cash + ST investments); positive = net debt | snapshot |
|
||||
| Net debt / EBITDA | net debt / TTM EBITDA | snapshot |
|
||||
| Share count Δ YoY | shares outstanding vs year ago | snapshot |
|
||||
| Trailing P/E | price / TTM diluted EPS | request time |
|
||||
| FCF yield | TTM FCF / est. market cap | request time |
|
||||
| Est. market cap | issuer-wide shares outstanding × ticker price | request time |
|
||||
| Earnings surprise history | last 4+ from `earnings_events` | query |
|
||||
|
||||
**Market cap is an estimate** (issuer-wide shares outstanding × one ticker's price —
|
||||
approximate for multi-class issuers). Share count comes from a single consolidated
|
||||
value, not a class sum: prefer the one `dei:EntityCommonStockSharesOutstanding`
|
||||
cover-page fact; if absent (e.g. Alphabet) fall back to
|
||||
`us-gaap:CommonStockSharesOutstanding` at period end. companyfacts is
|
||||
non-dimensional, so class-specific facts can't be summed reliably — never do that,
|
||||
and never substitute weighted-average/diluted shares; if conflicting values remain,
|
||||
store null. Label it "est." in the UI and round aggressively rather than withholding
|
||||
it; false precision is the failure mode, not the approximation.
|
||||
|
||||
**Units follow existing app conventions:** percentages are percentage points
|
||||
(21.0 = 21%), P/E and net-debt/EBITDA are multiples, market cap and net debt are
|
||||
dollars.
|
||||
|
||||
Deliberately **excluded**: ROIC (invested-capital/NOPAT normalization too noisy),
|
||||
gross margin (COGS tagging too inconsistent), any new composite score.
|
||||
|
||||
## Peer comparison (read-time only)
|
||||
|
||||
- Peer group = tracked-universe issuers sharing the **first two SIC digits**,
|
||||
**deduplicated by CIK** — GOOG and GOOGL are one issuer, one observation, in
|
||||
medians, percentiles and peer_count.
|
||||
- Computed at read time from current snapshots — no aggregate tables until
|
||||
performance demonstrates a need.
|
||||
- Medians exclude null/invalid values. **Fewer than 5 valid peer issuers → omit
|
||||
the peer result entirely** rather than showing a misleading universe comparison.
|
||||
- Percentile direction respects metric polarity (higher-is-better for FCF yield,
|
||||
lower-is-better for P/E and leverage).
|
||||
|
||||
## API contract (additive v1)
|
||||
|
||||
Every existing top-level field is preserved unchanged (name, type, position) —
|
||||
backend and frontend ship independently, no breaking interval. New objects, exact
|
||||
names and types:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
// ...all existing legacy fields, unchanged...
|
||||
"earnings": {
|
||||
"next": {"date": "YYYY-MM-DD", "session": "bmo|amc|unknown", "days_until": 12} | null,
|
||||
"recent": [ // newest first, max 4, may be empty
|
||||
{"announce_date": "YYYY-MM-DD", "period_end": "YYYY-MM-DD|null",
|
||||
"eps_estimate": 1.02|null, "eps_actual": 1.10|null, "surprise_pct": 7.8|null}
|
||||
]
|
||||
},
|
||||
"metrics": [ // fixed row set — every key always present, value null when unavailable
|
||||
{
|
||||
"key": "revenue_growth_yoy", // revenue_growth_yoy | eps_growth_yoy | operating_margin |
|
||||
// fcf_margin | net_debt | net_debt_to_ebitda | share_count_change_yoy
|
||||
"value": 18.0, // number | null — pp / multiples / dollars per units above
|
||||
"history": [ // oldest→newest, max 4 points, [] when unavailable
|
||||
{"period_end": "YYYY-MM-DD", "value": 8.0}
|
||||
],
|
||||
"industry": { // object | null — null when < 5 valid peer issuers (CIK-deduped)
|
||||
"label": "SIC 73 peers", // truthful 2-digit group label — grouping IS 2-digit,
|
||||
// so no 4-digit description like "Prepackaged Software"
|
||||
"median": 11.0,
|
||||
"favorable_percentile": 82, // 0-100, polarity-aware (higher = more favorable)
|
||||
"peer_count": 12 // issuers, not tickers
|
||||
},
|
||||
"period_end": "YYYY-MM-DD|null",
|
||||
"filed_date": "YYYY-MM-DD|null",
|
||||
"source": "sec|dolt|legacy_api"
|
||||
}
|
||||
],
|
||||
"valuation": { // object | null (null until SEC snapshots exist, phase A3); same industry sub-object rules
|
||||
// computed at REQUEST TIME from stored snapshots + latest PostgreSQL close —
|
||||
// no valuation cache or table; unaffected by SEC availability
|
||||
"pe": 29.2|null, "fcf_yield": 3.8|null,
|
||||
"market_cap_est": 1.2e9|null, // estimated — UI labels "est."
|
||||
"pe_industry": {...}|null, "fcf_yield_industry": {...}|null,
|
||||
"price_date": "YYYY-MM-DD" // close used for the ratios
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Null/freshness semantics: absent data is `null` with the row still present (the UI
|
||||
shows "n/a", never hides rows); every metric carries its own source, period and
|
||||
filing date — no panel-wide source label. The objects may serve partial data during
|
||||
rollout (e.g. `earnings` live, `metrics` still `legacy_api`); the shape never
|
||||
changes.
|
||||
|
||||
## UI — `frontend/src/components/ticker/FundamentalsPanel.tsx`
|
||||
|
||||
One distinctive visual device — the **Reference Rails** — in an otherwise restrained
|
||||
panel. Preserve the app's dark glass styling and numeric typography.
|
||||
|
||||
```
|
||||
Fundamentals
|
||||
Growth accelerating · margins improving · valuation priced above peers
|
||||
Next earnings Aug 3 · AMC EPS surprises ▂ ▅ ▃ ▆
|
||||
|
||||
Operating trend less favorable ← ref → more favorable
|
||||
Revenue growth 18%
|
||||
───────────────│━━━━● +3pp vs prior · accelerating
|
||||
Share count YoY −1.7%
|
||||
───────────────│━━━━● buying back
|
||||
|
||||
Valuation & balance less favorable ← median → more favorable
|
||||
P/E 29.2×
|
||||
────●━━━━━━━━━━│──── priced above peers · median 23.5× · 12 peers
|
||||
```
|
||||
|
||||
- Growth and margins: horizontal rails compare the latest value with the prior
|
||||
quarter or prior-period average; share-count YoY compares with zero. The rail
|
||||
is normalized so right is always more favorable, including buybacks.
|
||||
- P/E, FCF yield and leverage: horizontal favorable-percentile rails with a
|
||||
peer-median marker. No decorative rail when `industry` is null (< 5 peers).
|
||||
- Every row keeps the exact value and one deterministic comparison caption;
|
||||
missing values render `n/a`, and insufficient peers render `peers n/a`.
|
||||
- Earnings: four bars around a shared zero baseline — cyan beats, coral misses, gray
|
||||
unavailable — plus next date and BMO/AMC session countdown.
|
||||
- Accessibility: color is always paired with text; neutral/ambiguous stays gray;
|
||||
rails and earnings bars expose complete ARIA descriptions.
|
||||
- Remove the hard-coded "FMP" source label; surface filing and price-date
|
||||
provenance in the footer.
|
||||
|
||||
**Deterministic reads — one shared rule set.** Implement as a single function with
|
||||
named constants; the metric reads and the header sentence use identical outputs. No
|
||||
LLM, no new composite score. Defaults (tunable constants, not scattered literals):
|
||||
|
||||
- A series read requires ≥ 3 periods; otherwise show "—" and no read.
|
||||
- Growth metrics (pp): latest − prior ≥ +2.0 → "accelerating";
|
||||
≤ −2.0 → "decelerating"; else "steady".
|
||||
- Margins (latest vs mean of prior periods, pp): ≥ +1.0 → "improving";
|
||||
≤ −1.0 → "deteriorating"; else "stable" (phrased "above/below own average"
|
||||
where the layout calls for it).
|
||||
- Share count YoY: > +1.0% → "N% dilution"; < −1.0% → "buying back"; else "flat".
|
||||
- Peer-relative: favorable_percentile ≥ 60 → favorable ("above peers");
|
||||
≤ 40 → adverse ("priced above peers" for P/E, "elevated leverage" for
|
||||
net-debt/EBITDA); else "in line".
|
||||
- Header sentence: join the growth read, margin read and peer-relative valuation
|
||||
read with " · ", omitting segments that have no read (e.g. "Growth accelerating
|
||||
· margins stable · valuation above industry median"). **Segment sources are
|
||||
fixed:** growth = revenue growth read; margins = operating margin read;
|
||||
valuation = P/E peer-relative read, falling back to FCF yield when P/E is null.
|
||||
This keeps the header unambiguous when sibling metrics (EPS vs revenue growth,
|
||||
P/E vs FCF yield) point in different directions.
|
||||
|
||||
## Decommissioning (end of workstream A)
|
||||
|
||||
Remove completely: FMP (`app/providers/fmp.py`), Finnhub + Alpha Vantage
|
||||
(`app/providers/fundamentals_chain.py`), their config keys (`app/config.py`), and
|
||||
their wiring in `app/scheduler.py`, `app/routers/ingestion.py`,
|
||||
`app/services/ticker_universe_service.py`. Retain: Alpaca (prices), FRED,
|
||||
sentiment provider, Telegram. Note: decommissioning does **not** depend on
|
||||
workstream B — Alpaca remains the price source throughout.
|
||||
|
||||
## Rollout
|
||||
|
||||
**Workstream A:**
|
||||
|
||||
- A0. License review **DONE** (earnings approved for private/internal use under
|
||||
CC BY-SA 4.0, no redistribution — see Licensing above). The Dolt version,
|
||||
persistent `DOLT_DATA_DIR`, clone, and production checks are captured in
|
||||
`deploy/provision_fundamentals.sh` and `docs/fundamentals-deployment.md`.
|
||||
- A1. Migration 026, import-run framework.
|
||||
- A2. Earnings ingestion in shadow (writes `earnings_events`, prod untouched);
|
||||
verify forward-calendar coverage and rescheduling behavior.
|
||||
- A3. SEC daily job in shadow (writes `fundamental_snapshots`). **Primary technical
|
||||
risk here: Q4 derivation and fiscal-period alignment** — non-calendar fiscal years,
|
||||
restatements/amendments, and XBRL unit/dimension variants; budget accordingly.
|
||||
- A4. API v1 + FundamentalsPanel + peer comparison — served from snapshots and
|
||||
earnings_events, independent of the scoring cutover (the additive API supports
|
||||
partial data). UI value ships before anything touches scoring inputs.
|
||||
- A5. **Score-parity gate** → `fundamental_data` cutover: compute candidate
|
||||
pe_ratio/revenue_growth/earnings_surprise from SEC/Dolt side by side with the
|
||||
API values across the tracked universe, report per-field deltas and resulting
|
||||
fundamental-score/ranking changes, require explicit approval. Definition
|
||||
changes (e.g. TTM vs provider convention) called out, not averaged away.
|
||||
**Status 2026-07-24: the gate has been exercised and the evidence supports
|
||||
approval** — see the handoff section below. Step (c) is implemented behind the
|
||||
default-off `fundamental_data_sec_dolt_cutover_enabled` SystemSetting; the
|
||||
remaining production action is flipping that switch on and observing it.
|
||||
- A6. **DONE 2026-08-07.** FMP/Finnhub/Alpha Vantage removed, along with the
|
||||
weekly `fundamental_collector` job, the A5 cutover toggle (SEC+Dolt is now the
|
||||
unconditional path) and the parity report. Migration `029` tombstoned the two
|
||||
behavior-bearing settings rows for the rollback window and `030` dropped them
|
||||
once the deploy was confirmed healthy; the archived parity bundles stay as the
|
||||
A5 evidence trail.
|
||||
|
||||
**Workstream B — DROPPED 2026-08-07.** The phases below are recorded for anyone
|
||||
who revisits the decision; none of them are scheduled work.
|
||||
|
||||
- ~~B0. Stocks clone (~4.7 GB) provisioned; migration 027.~~
|
||||
- ~~B1. OHLCV + split adjustment in shadow (writes `ohlcv_source_bars` only; Alpaca
|
||||
keeps owning `ohlcv_records`); historical backfill.~~
|
||||
- ~~B2. Reconciliation window (≥ 2 weeks) vs Alpaca; review validation summaries.~~
|
||||
- ~~B3. Promote Dolt as historical OHLCV source (canonical rebuilt from raw source
|
||||
bars + splits); morning pipeline → 03:00.~~
|
||||
|
||||
### Why B was dropped
|
||||
|
||||
Reviewed after A6 shipped. Four reasons, in order of weight:
|
||||
|
||||
1. **Its motivation no longer exists.** B was scoped inside a plan whose goal was
|
||||
killing the quota-limited free-tier APIs. Alpaca was never one of them, and the
|
||||
plan always said so (§ Decommissioning: "Alpaca remains the price source
|
||||
throughout"). A6 achieved the goal. What remained was swapping one working
|
||||
price source for another.
|
||||
2. **Its only concrete benefit is reachable far more cheaply.** The prize was
|
||||
`corporate_actions`, the documented fix for the KLAC-class post-filing split
|
||||
(TTM EPS pre-split vs a post-split price → P/E 6.19 instead of ~13, invisible to
|
||||
snapshots). That needs *split events*, not 4.7 GB of bars — and the Alpaca SDK
|
||||
already in the venv exposes them via
|
||||
`alpaca.data.historical.corporate_actions.CorporateActionsClient.get_corporate_actions`
|
||||
with `CorporateActionsRequest` / `CorporateActionsType`. See the follow-up below.
|
||||
3. **The benefit is small.** Fundamentals carry 20% of the composite, P/E is one of
|
||||
three fundamental inputs, and only names that split between their last 10-Q and
|
||||
today are affected — a handful at a time, self-correcting at the next filing.
|
||||
4. **B would add a risk the current setup does not carry.** By design a newly
|
||||
published split rewrites a symbol's entire adjusted history. A backtest↔prod
|
||||
parity guard exists precisely because changed history invalidates comparisons;
|
||||
B makes history mutable as a routine event. It also needs its own license
|
||||
review — the A0 CC BY-SA decision covers only `post-no-preference/earnings`.
|
||||
|
||||
**Optional follow-up, not scheduled:** a small `corporate_actions` table populated
|
||||
from Alpaca, used to null or correct P/E when a split post-dates the newest
|
||||
snapshot. Roughly a day's work; captures essentially all of B's value with no
|
||||
clone, no `ohlcv_source_bars`, no split-adjustment pipeline and no reconciliation
|
||||
window. Worth doing only if the wart starts costing something — it has been visible
|
||||
and harmless since July 2026. Note that migration numbering has moved on: head is
|
||||
`030`, so any such table would be `031+`, not the `027` named below.
|
||||
|
||||
## Test plan
|
||||
|
||||
- Daily SEC job: changed revision imports; unchanged conditional-HTTP check is a
|
||||
`no_op` with zero downloads and zero row changes; validation failure leaves
|
||||
production untouched; source unavailable still runs the local
|
||||
`fundamental_data` refresh (step c, post-activation); before activation the job
|
||||
never writes `fundamental_data`.
|
||||
- Valuation endpoint returns identical values with SEC reachable and unreachable
|
||||
(pure PostgreSQL computation); no valuation rows exist in any table.
|
||||
- Multi-class tickers resolve to the same CIK snapshots; peer medians and
|
||||
peer_count are CIK-deduplicated (GOOG+GOOGL = one observation).
|
||||
- Earnings rescheduling: a moved future date replaces the old row atomically; a
|
||||
cancelled date disappears; historical results are never touched.
|
||||
- Amendment selection: for a period with multiple accessions, the newest valid
|
||||
accepted_at wins at read time; older rows remain unchanged.
|
||||
- History arrays are chronological, ≤ 4 points.
|
||||
- Percentage-point units stay compatible with existing formatters and scoring
|
||||
inputs.
|
||||
- Deterministic reads: threshold boundary cases (exactly +2.0pp, exactly 60th
|
||||
percentile) resolve per the stated rules; header uses identical outputs and
|
||||
falls back from P/E to FCF yield for the valuation segment when P/E is null.
|
||||
- Peer comparison disappears below 5 peer issuers; favorable-percentile direction
|
||||
correct for both polarities.
|
||||
- ~~Workstream B: split-adjusted OHLCV matches Alpaca on representative normal /
|
||||
split / reverse-split symbols.~~ (dropped)
|
||||
- UI states: positive, adverse, neutral, insufficient history, insufficient
|
||||
peers; mobile layout; non-color accessibility.
|
||||
- Unit, integration, scheduler and frontend suites pass.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- App works normally with Dolt/DoltHub/SEC unreachable.
|
||||
- Re-running the same revision: zero duplicate or changed rows.
|
||||
- **Upcoming earnings dates present and timely for the tracked universe** — the
|
||||
forward calendar is the hardest thing to replace and gates decommissioning.
|
||||
- Coverage meets the tracked-universe target; scheduler runs cleanly with
|
||||
FMP/Finnhub/AV keys removed from the environment.
|
||||
- Score-parity diff reviewed and approved before `fundamental_data` cutover.
|
||||
- Scheduled imports never block the API event loop.
|
||||
|
||||
## Handoff — remaining work after the A5 parity investigation (2026-07-24)
|
||||
|
||||
The 2026-07-23 parity report surfaced coverage gaps and wrong values; a nine-pass
|
||||
investigation traced every one to parser/identity bugs (not source data), fixed them,
|
||||
and reparsed production twice. Full evidence trail:
|
||||
`reports/fundamentals-parity-20260723-findings.md` (root causes, decisions, validation)
|
||||
plus the before/after reports (`fundamentals-parity-20260723T…` / `…20260724T….json`).
|
||||
Post-fix: candidate scores 504 of 511 vs legacy's 507 (gap = PSKY/Q new registrants +
|
||||
FITB, all explained); revenue-growth agreement 0.0038 median abs delta where both exist.
|
||||
Dennis reviewed the evidence 2026-07-24 and directed proceeding to cutover.
|
||||
|
||||
**Task 1 — A5 activation: DONE.** Implemented 2026-07-24, switched on and observed
|
||||
in production, and made unconditional by A6 (2026-08-07) — there is no longer a
|
||||
switch, an Admin card, or a weekly legacy collector to skip. The local refresh of
|
||||
`fundamental_data` derives `pe_ratio` and `market_cap` from newest valid snapshots ×
|
||||
latest PostgreSQL close, `revenue_growth` from snapshots, and
|
||||
`earnings_surprise`/`next_earnings_date` from `earnings_events`; it marks affected
|
||||
cached fundamental scores stale and runs identically when SEC is unreachable.
|
||||
It consumes `fundamentals_derivation.derive()` outputs, NOT raw snapshot fields —
|
||||
that path carries the split guard (`ttm_diluted_eps` nulls when contaminated, with
|
||||
`ttm_diluted_eps_caveat`) and the multi-class share fallback (`shares_outstanding` +
|
||||
`shares_outstanding_estimated`). See `docs/fundamentals-deployment.md` for current
|
||||
operations and rollback.
|
||||
|
||||
**Task 2 — A6 decommissioning: DONE 2026-08-07.** The cutover ran on and was
|
||||
observed in production, so the legacy providers, their config/env keys, the weekly
|
||||
collector job and the parity report were all removed. Two consequences to carry:
|
||||
(1) `fundamental_data` now has no provider fallback — recovery is restore-from-backup;
|
||||
(2) disabling **SEC Fundamentals Import** stops the SEC fetch only, because the local
|
||||
cache refresh was deliberately moved outside the job-enable check. No follow-ups
|
||||
remain: migration `030` dropped the tombstone rows after the deploy was verified.
|
||||
|
||||
**Known caveats to carry (documented in the findings report, not bugs to fix):**
|
||||
- KLAC-class post-filing splits: P/E wrong until the next 10-Q; undetectable from
|
||||
snapshots. Still open and still harmless. The fix, if ever wanted, is a small
|
||||
`corporate_actions` table fed from Alpaca — **not** workstream B, which was
|
||||
dropped; see § Why B was dropped.
|
||||
- BRK-B: no share count exists anywhere in companyfacts → no market cap, correctly.
|
||||
- FITB: unscored (split guard + no taggable revenue) — the one name that lost its
|
||||
score relative to legacy; composite renormalises.
|
||||
- Share-change guard at 25% nulls P/E for stock-funded M&A too (COF, WAT…);
|
||||
revisit only if the ~3% universe hit-rate proves painful.
|
||||
- `sec_cik_overrides` SystemSetting pins XOM → 34088 (applied in prod); the
|
||||
`no_xbrl_filings` SystemEvent says when a new pin is needed.
|
||||
- After any future parser change, stored rows need `scripts/reparse_fundamentals.py`
|
||||
(dry-run default; `--apply` rewrites) — snapshots are otherwise immutable.
|
||||
|
||||
## Deferred (explicitly, until a concrete need appears)
|
||||
|
||||
- Workstream B: **dropped** 2026-08-07, not deferred — see § Why B was dropped.
|
||||
- Exact byte-level source replay of historical imports; permanent archive store.
|
||||
- Point-in-time backtest enforcement (`accepted_at` is stored now; derivation and
|
||||
backtest visibility rules are built only when fundamentals enter
|
||||
scoring/backtesting).
|
||||
- Fundamental metrics in the score; sector-relative scoring.
|
||||
- Aggregate/rollup tables for peer statistics.
|
||||
- Any valuation cache or table (request-time computation from snapshots + latest
|
||||
close suffices).
|
||||
- A dedicated conflicts table (validation JSON + logs suffice).
|
||||
@@ -0,0 +1,252 @@
|
||||
# A3 design — SEC fundamentals importer
|
||||
|
||||
Status: **design APPROVED 2026-07-22 — three decisions signed off (daily-index
|
||||
fetch, primary-period-only snapshots, full-history backfill) + four review
|
||||
correctness fixes folded in (composite revision incl. universe fingerprint;
|
||||
submissions pagination shards for full history; index↔Company-Facts consistency
|
||||
gate; insert-only immutability with discrepancy reporting; deterministic cash/debt
|
||||
composition). Ready to implement.**
|
||||
Companion to `docs/dolt-integration-plan.md` (workstream A, phase A3). Grounded in
|
||||
live SEC data probes (Apple CIK 0000320193, company_tickers, submissions, daily-index).
|
||||
|
||||
## Objective (unchanged from the plan)
|
||||
|
||||
Populate `fundamental_snapshots` (CIK-keyed, one immutable row per accession)
|
||||
and `tickers.cik/sic/sic_description` from SEC data, as a `SourceImporter`
|
||||
plugging into the A1 framework. Shadow only (A3): nothing reads snapshots until
|
||||
A4; `fundamental_data` is untouched until the A5 parity gate. All new metrics
|
||||
are display-only.
|
||||
|
||||
## What the SEC data actually looks like (probed, not assumed)
|
||||
|
||||
`data.sec.gov/api/xbrl/companyfacts/CIK##########.json` — one JSON per **issuer
|
||||
(CIK)** aggregating every period across every filing. Shape:
|
||||
`facts.us-gaap.<Concept>.units.<unit>[] = {start, end, val, fy, fp, form, filed, accn, frame}`.
|
||||
|
||||
Ground-truth findings that drive the design:
|
||||
|
||||
1. **`fp` is only `Q1|Q2|Q3|FY` — there is no `Q4`.** Q4 must be derived.
|
||||
2. **`fy`/`fp` are the *filing's* fiscal context, not each fact's period.** Proven:
|
||||
Apple's FY2019 10-K carries a discrete Q3-FY2018 revenue fact
|
||||
(`start 2018-07-01, end 2018-09-29, val 62.9B`) tagged `fp=FY` — it's a
|
||||
comparative. **Period identity lives in `(start, end)` + the filing's
|
||||
`reportDate`, never in `fp/fy`.** Selecting values by `fp` would silently mix
|
||||
comparatives into the wrong period.
|
||||
3. SEC provides **both** discrete 3-month facts **and** YTD-cumulative facts
|
||||
(Apple Q2 FY26: YTD `254,940` over 6mo *and* discrete `111,184` over 3mo;
|
||||
`143,756 + 111,184 = 254,940`). This confirms the stored-YTD schema: store
|
||||
cumulative YTD per filing, derive discretes/Q4/TTM at read time.
|
||||
4. Instant facts (`dei:EntityCommonStockSharesOutstanding`) end on the **cover
|
||||
date** (2026-04-17), which differs from `period_end` (2026-03-28) → the
|
||||
`shares_outstanding_date` column added in migration 026.
|
||||
5. **No conditional-GET support:** the companyfacts endpoint returns no `ETag`
|
||||
and no `Last-Modified`. AAPL's file is 3.75 MB. So ~505 unconditional fetches
|
||||
≈ 0.5–1.5 GB *per run* — the plan's "conditional HTTP no-op" is impossible on
|
||||
this endpoint. This is the fact that decides the fetch strategy (below).
|
||||
6. `submissions/CIK##########.json` supplies `sic`, `sicDescription`,
|
||||
`fiscalYearEnd` (e.g. `0926`), and per-accession `reportDate` +
|
||||
`acceptanceDateTime` — the keys for period selection and `accepted_at`.
|
||||
7. `company_tickers.json` uses **dash** tickers (`BRK-B`, `BRK-A`) and maps
|
||||
`GOOGL`/`GOOG` to the **same** `cik_str` (1652044). The ticker→CIK join reuses
|
||||
the earnings importer's `normalise_symbol` (dot→dash), so both sides match.
|
||||
|
||||
## Decision 1 (APPROVED) — fetch strategy: EDGAR daily-index driven
|
||||
|
||||
**Plan said** bulk `companyfacts.zip` + ETag no-op. **Reality:** the data.sec.gov
|
||||
endpoints expose no validators, and the bulk zip is multi-GB and changes ~daily
|
||||
(all of EDGAR), so ETag would rarely match → near-daily multi-GB download to get
|
||||
505 issuers. Per-CIK *conditional* fetch is impossible (finding 5). Per-CIK
|
||||
*unconditional* is 0.5–1.5 GB every night.
|
||||
|
||||
**Recommended:** drive off the **EDGAR daily-index** (`daily-index/YYYY/QTRn/
|
||||
form.YYYYMMDD.idx` — fixed-width Form/Company/CIK/Date/accession, ~3300 rows/day,
|
||||
confirmed). Each run:
|
||||
|
||||
- `detect_revision` → a **composite revision**, not just the date:
|
||||
`latest-index-date` + a hash of the index content processed this run + a
|
||||
**fingerprint of the tracked symbol→CIK set**. The CIK fingerprint is essential:
|
||||
a newly added ticker changes the revision and forces a run, so a new ticker is
|
||||
never `no_op`'d away or starved waiting for its issuer to file. Equal composite
|
||||
revision → `no_op`.
|
||||
- **No backfill sentinel.** The *absence of a prior promoted run* is what triggers
|
||||
the initial full-history backfill; `source_max_date` records the processed index
|
||||
date each run.
|
||||
- `stage` → for each index date since the last processed one, parse the form
|
||||
index, keep rows where `form ∈ {10-K, 10-Q, 10-K/A, 10-Q/A}` **and** CIK ∈
|
||||
tracked set, then fetch `companyfacts/CIK.json` for **only those few issuers**
|
||||
and extract their newly-reported period(s). Most nights this is a handful of
|
||||
issuers → near-zero transfer, respectful of SEC fair-access.
|
||||
- **First run (backfill)**: no prior promoted run → fetch companyfacts for all
|
||||
tracked CIKs once (~1 GB one-time) and seed **full** history. Full history needs
|
||||
the paginated submissions shards — see "CIK resolution" below.
|
||||
|
||||
Why this over the alternatives: transfer scales with *filings*, not with all of
|
||||
EDGAR or with the universe size every night; it restores the revision/no_op
|
||||
model; and it's the lightest load on SEC. Cost: daily-index parsing + date
|
||||
bookkeeping (store last-processed index date in `data_import_runs` /
|
||||
settings). **This deviates from the plan's "bulk zip" — requesting sign-off.**
|
||||
|
||||
## Decision 2 (APPROVED) — snapshot mapping: primary-period, YTD, immutable
|
||||
|
||||
One `fundamental_snapshots` row per accession, representing the filing's
|
||||
**primary current period only** (not its comparatives):
|
||||
|
||||
- **Select the primary period by `end == submissions.reportDate[accn]`** (finding
|
||||
2), *not* by `fp/fy`. `fiscal_period` label comes from the filing's own `fp`
|
||||
(a 10-Q's own `fp` matches its current quarter; a 10-K → `FY`);
|
||||
`fiscal_year`/`period_start`/`period_end` from the selected facts + submissions.
|
||||
- **Duration facts → cumulative YTD.** For each concept, pick the duration fact
|
||||
with `accn == thisFiling`, `end == reportDate`, and `start ≈ fiscal-year start`
|
||||
(derived from `fiscalYearEnd`), sanity-checked by span length (Q1≈3mo, Q2≈6mo,
|
||||
Q3≈9mo, FY≈12mo). **If the YTD fact is absent, store null — never a discrete
|
||||
masquerading as cumulative** (that would poison read-time differencing).
|
||||
- **Balance-sheet instants → at `end == reportDate`.** `shares_outstanding` is
|
||||
the exception: prefer the `dei:EntityCommonStockSharesOutstanding` cover-page
|
||||
fact and store *its own* `end` in `shares_outstanding_date` (cover date ≠
|
||||
period_end); when there is no dei fact (e.g. Alphabet) fall back to
|
||||
`us-gaap:CommonStockSharesOutstanding` at `reportDate`. A single consolidated
|
||||
value — never a class sum (companyfacts is non-dimensional) nor
|
||||
weighted-average/diluted; conflicting values → null.
|
||||
- **Amendments:** a real `10-K/A` / `10-Q/A` is a new accession → a new immutable
|
||||
row for the same `(cik, fy, fp)`; readers pick the newest valid `accepted_at`.
|
||||
- **Out of scope (stated, not silent):** restatements that appear *only* as
|
||||
comparatives inside a later normal filing are **not** captured — only a real
|
||||
amendment updates a prior period. This narrows the plan's "newest accepted_at
|
||||
per period" to amendment-driven updates; a deliberate KISS boundary.
|
||||
- **Immutable means insert-only, not upsert.** `promote` **inserts** new accession
|
||||
rows with `ON CONFLICT (accession) DO NOTHING`. An accession never mutates: if a
|
||||
re-fetch reconstructs *different* values for an accession already stored, that is
|
||||
a **discrepancy to report** (into `validation_json` + a system event), never a
|
||||
silent overwrite, and the original `import_run_id` is never replaced. (Ordinary
|
||||
updates arrive as a *new* amendment accession, which is a new row.)
|
||||
|
||||
## Read-time derivation (constrains the importer; built in A4)
|
||||
|
||||
From the per-accession YTD rows, all at read time (newest `accepted_at` per
|
||||
period), following the schema decision already in the plan:
|
||||
|
||||
- discrete quarter = YTD(Qn) − YTD(Qn−1); **Q4 = FY − YTD(Q3)**.
|
||||
- TTM = sum of the trailing four discrete quarters (e.g. TTM@Q2 = FY(prev) +
|
||||
YTD(Q2) − YTD(Q2 prev year)).
|
||||
- YoY = period vs same period a year earlier.
|
||||
- **Hard rule the importer must enable: any missing period in a run → the derived
|
||||
value is `null`, never a partial number.** So the importer must aim for
|
||||
complete consecutive quarter runs per issuer and report gaps.
|
||||
|
||||
## Metric tag catalog (prioritized us-gaap tags + fallbacks)
|
||||
|
||||
Tagging is inconsistent across issuers (the plan's known risk). Each metric
|
||||
resolves through an ordered tag list; first present wins; unit-checked.
|
||||
|
||||
| Snapshot field | Primary tag | Fallbacks | Unit |
|
||||
|---|---|---|---|
|
||||
| revenue | `RevenueFromContractWithCustomerExcludingAssessedTax` | `Revenues`, `SalesRevenueNet` | USD |
|
||||
| net_income | `NetIncomeLoss` | — | USD |
|
||||
| operating_income | `OperatingIncomeLoss` | — | USD |
|
||||
| diluted_eps | `EarningsPerShareDiluted` | — | USD/shares |
|
||||
| cfo | `NetCashProvidedByUsedInOperatingActivities` | `...ContinuingOperations` | USD |
|
||||
| capex | `PaymentsToAcquirePropertyPlantAndEquipment` | `PaymentsToAcquireProductiveAssets` | USD |
|
||||
| depreciation_amortization | `DepreciationDepletionAndAmortization` | `DepreciationAmortizationAndAccretionNet`, `DepreciationAndAmortization` | USD |
|
||||
| cash_and_st_investments | see composition rule | — | USD |
|
||||
| total_debt | see composition rule | — | USD |
|
||||
| shares_outstanding | `dei:EntityCommonStockSharesOutstanding` | — | shares |
|
||||
|
||||
**Composite fields — deterministic, aggregate-first, no double counting.** Each
|
||||
source tag contributes at most once:
|
||||
|
||||
- `cash_and_st_investments` = `CashAndCashEquivalentsAtCarryingValue`
|
||||
**+ short-term investments**, where ST investments = the **first present** of
|
||||
[`ShortTermInvestments`, `MarketableSecuritiesCurrent`] — never both summed.
|
||||
- `total_debt` = **long-term component + short-term component**, where
|
||||
- long-term = first present of [`LongTermDebt` (the aggregate, already includes
|
||||
current + noncurrent portions), **else** (`LongTermDebtNoncurrent` +
|
||||
`LongTermDebtCurrent`)];
|
||||
- short-term borrowings = first present of [`ShortTermBorrowings`,
|
||||
`CommercialPaper`] (0 if neither).
|
||||
So the long-term aggregate and its components are mutually exclusive, and CP vs
|
||||
short-term-borrowings is a single pick — nothing is counted twice.
|
||||
|
||||
EBITDA (for net-debt/EBITDA) is derived at read time = operating_income + D&A.
|
||||
Concepts absent for an issuer → that field is null (display-only; no synthesis).
|
||||
The exact tag lists live as named constants, tunable without touching logic.
|
||||
|
||||
## Fiscal-period identity
|
||||
|
||||
`fiscalYearEnd` (MMDD from submissions) anchors the fiscal-year start for YTD
|
||||
span checks and Q4 derivation. Non-calendar fiscal years (Apple's Sept) are
|
||||
handled because we key on `(start, end)` + `reportDate`, not calendar quarters.
|
||||
`fiscal_year`/`fiscal_period` are stored from the filing's own `fy`/`fp` for its
|
||||
primary period (safe — a filing's own context is correct for its current period).
|
||||
|
||||
## CIK resolution & tickers backfill
|
||||
|
||||
- From `company_tickers.json`: `normalise_symbol(ticker) → cik_str`. Set
|
||||
`tickers.cik` for each tracked ticker (multi-class share one CIK).
|
||||
- From `submissions/CIK.json`: `sic`, `sicDescription`, `fiscalYearEnd` →
|
||||
`tickers.sic/sic_description` (+ fiscal anchor for YTD/Q4).
|
||||
- **Submissions is paginated — full history needs the shards.** `filings.recent`
|
||||
holds only the **latest 1000** filings (verified: Apple `recent` = 1000). Older
|
||||
accessions live in `filings.files[]` = `[{name, filingFrom, filingTo,
|
||||
filingCount}]` (e.g. `CIK0000320193-submissions-001.json`, 1236 filings
|
||||
1994–2015), each a bare object with the **same parallel arrays** including
|
||||
`reportDate`, `acceptanceDateTime`, and `isXBRL`. The full-history backfill must
|
||||
**follow every `filings.files[].name`** to obtain period identity + `accepted_at`
|
||||
+ `isXBRL` for pre-1000 accessions. Incremental runs only need `recent`.
|
||||
- Refreshed by the SEC job; a newly added ticker self-resolves on its next run
|
||||
(the CIK fingerprint in the revision forces that run) — until then its snapshots
|
||||
are absent → metrics null, per the plan.
|
||||
|
||||
## SourceImporter mapping (source = `sec_facts`)
|
||||
|
||||
- `detect_revision` → latest daily-index date (or `backfill` sentinel on first run).
|
||||
- `stage` → resolve tracked CIKs; (incremental) parse indices since last date →
|
||||
tracked filers → fetch their companyfacts → build per-accession snapshot rows;
|
||||
(backfill) fetch all tracked companyfacts. In-memory staged set (KISS, per A1).
|
||||
- `validate` (fail-closed) → tracked-universe **coverage floor** (issuers with ≥1
|
||||
snapshot); **unit/period sanity** (YTD spans within tolerance; EPS in USD/shares);
|
||||
**no duplicate accession**; **filings skipped for missing period identity are
|
||||
counted in `validation_json`** (carry-forward from A1 review); an unexpected
|
||||
companyfacts shape (missing `facts`/`units`) stops promotion.
|
||||
- **Index↔Company-Facts consistency gate (the daily index and Company Facts are
|
||||
separate SEC products that can lag each other):** for every tracked index
|
||||
accession marked `isXBRL`, confirm that accession actually appears in the fetched
|
||||
companyfacts before promotion. If any is missing → **fail the run and retry
|
||||
later** — do **not** advance the revision and do **not** record an
|
||||
incomplete/null snapshot for it. Non-XBRL amendments are skipped with a recorded
|
||||
reason in `validation_json`. (The framework only stores the revision on a
|
||||
promoted run, so a failed consistency check naturally leaves the revision behind
|
||||
for retry.)
|
||||
- `promote` → **insert** snapshot rows (`ON CONFLICT (accession) DO NOTHING`;
|
||||
immutable — see Decision 2), stamped `import_run_id`; refresh
|
||||
`tickers.cik/sic/sic_description`. A re-fetch that reconstructs different values
|
||||
for an existing accession is reported as a discrepancy, never a silent mutation.
|
||||
Non-destructive (append-only accessions) — no future-row deletion like earnings.
|
||||
|
||||
## SEC fair-access (operational, per the plan's non-negotiable)
|
||||
|
||||
Identifying `User-Agent` with contact email on every request; well under 10 req/s
|
||||
with spacing; exponential backoff on 429; **403 → alert and stop, never
|
||||
retry-loop** — with one carved-out exception: `www.sec.gov/Archives` is served
|
||||
from an S3 bucket without a `ListBucket` grant, so an **absent** file 403s with
|
||||
S3's `AccessDenied` XML rather than 404 (every weekend/holiday daily index does
|
||||
this). That one shape is read as "missing"; a real rejection is the WAF's
|
||||
`text/html` "Undeclared Automated Tool" page and still stops the run.
|
||||
New config: `sec_user_agent`, `sec_request_spacing_seconds`,
|
||||
`sec_max_retries`. Keep only the last ~2 fetched artifacts on disk for debugging
|
||||
(reproducibility is the normalized Postgres rows, per the plan).
|
||||
|
||||
## Explicitly out of scope for A3
|
||||
|
||||
- `fundamental_data` cutover (A5 parity gate) — snapshots only in A3.
|
||||
- The read-time derivation, API object, and panel (A4).
|
||||
- Comparative-only restatements (Decision 2).
|
||||
- Point-in-time backtest enforcement (`accepted_at` stored, not yet enforced).
|
||||
|
||||
## Decisions (signed off 2026-07-22)
|
||||
|
||||
1. **Fetch** — EDGAR daily-index driven (Decision 1). Approved deviation from the
|
||||
plan's bulk zip.
|
||||
2. **Snapshot mapping** — primary-period-only per accession; comparative-only
|
||||
restatements out of scope (Decision 2). Approved.
|
||||
3. **Backfill depth** — seed **full** available history per issuer on first run
|
||||
(cheap to store; powers the quarter tape / multi-year YoY). Approved.
|
||||
@@ -0,0 +1,226 @@
|
||||
# Fundamentals production deployment
|
||||
|
||||
This is the one-time production setup for the Dolt earnings and SEC fundamentals
|
||||
imports. Since A6 (2026-08) these are the *only* fundamentals sources — the
|
||||
FMP/Finnhub/Alpha Vantage providers, the weekly legacy collector and the A5 parity
|
||||
report are gone, and the cache write path is unconditional. Do not add OS cron
|
||||
entries: the application scheduler owns both jobs.
|
||||
|
||||
## What the deployment adds
|
||||
|
||||
- `Dolt Earnings Import` runs daily at 02:30 America/New_York.
|
||||
- `SEC Fundamentals Import` runs daily at 04:00 America/New_York, then refreshes
|
||||
`fundamental_data` — the compat cache scoring reads — from stored snapshots,
|
||||
earnings events and closes.
|
||||
- Both jobs are visible, toggleable, and manually triggerable in Admin → Jobs.
|
||||
**Disabling the SEC job stops its SEC network fetch only**; the local cache
|
||||
refresh still runs, because prices and earnings move daily even when no filing
|
||||
does.
|
||||
- Cron expressions are editable in Admin → Schedule.
|
||||
- Every attempt is recorded in `data_import_runs`; failures also create a system
|
||||
event. A failed validation does not promote partial data.
|
||||
- An SEC filing still missing after the short publication-lag window enters
|
||||
`sec_filing_gaps`. The daily importer retries it automatically; affected
|
||||
tickers are excluded from actionable setups until a snapshot is recovered or
|
||||
a later valid 10-K/10-Q supersedes the gap. Migration `028` materializes older
|
||||
promoted gaps into this queue once, so setup reads never scan import history.
|
||||
- A gap that survives 14 days raises `filing_gap_aged` and, from that point,
|
||||
stops pausing setups **if** the issuer's own newest stored 10-K/10-Q is less
|
||||
than `GAP_GATE_RECENT_FILING_DAYS` (180) old. This is the hand-off from pause
|
||||
to alert, and it exists because the pause would otherwise be open-ended:
|
||||
SEC's per-company Company-Facts files can go stale indefinitely (2026-08: 43
|
||||
large caps whose Q2 10-Qs the `frames` API carried but whose
|
||||
`companyfacts/CIK*.json` never received), and the supersede rule needs a
|
||||
*successfully ingested* later filing, so a stale file swallows the next
|
||||
quarter too. Retrying is unaffected — the gap stays queued and a recovered
|
||||
filing still resolves it normally. An issuer with no filing that recent has no
|
||||
usable fundamentals at all and stays paused.
|
||||
|
||||
The systemd service uses one application worker. The import framework also holds
|
||||
a PostgreSQL advisory lock per source, so an overlapping manual/scheduled run is
|
||||
skipped safely.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
The production `.env` at `/opt/signalplatform/.env` must contain:
|
||||
|
||||
```dotenv
|
||||
DOLT_BINARY=/usr/local/bin/dolt
|
||||
DOLT_DATA_DIR=/var/lib/signal-platform/dolt
|
||||
DOLT_EARNINGS_SUBDIR=earnings
|
||||
DOLT_MIN_FREE_DISK_GB=5.0
|
||||
SEC_USER_AGENT=signal-platform/1.0 (contact: real-address@example.com)
|
||||
SEC_REQUEST_SPACING_SECONDS=0.2
|
||||
```
|
||||
|
||||
Use a real monitored contact address. Keep at least 5 GB free at the Dolt data
|
||||
path; 8–10 GB gives comfortable growth headroom. The data directory must stay
|
||||
outside `/opt/signalplatform`, because deployments use `rsync --delete` there.
|
||||
|
||||
`FMP_API_KEY`, `FINNHUB_API_KEY` and `ALPHA_VANTAGE_API_KEY` must be **removed**
|
||||
from this file. Nothing reads them any more, and leaving them installed is the
|
||||
one thing that would let a rolled-back pre-A6 process resume the legacy
|
||||
collector and overwrite the SEC/Dolt cache.
|
||||
|
||||
## One-time provisioning
|
||||
|
||||
First deploy the commit containing this bundle to production. Then SSH to the
|
||||
server and run:
|
||||
|
||||
```bash
|
||||
cd /opt/signalplatform
|
||||
sudo bash ./deploy/provision_fundamentals.sh
|
||||
sudo -u deploy bash ./deploy/provision_fundamentals.sh --check
|
||||
sudo systemctl restart signalplatform.service
|
||||
curl -fsS http://127.0.0.1:8998/api/v1/health
|
||||
```
|
||||
|
||||
The provisioner is idempotent. It installs the pinned Dolt version, creates the
|
||||
persistent directory as `deploy:deploy`, clones
|
||||
`post-no-preference/earnings`, configures a repository-local author identity for
|
||||
`dolt pull`, verifies free space and `.env`, and refuses an unexpected
|
||||
Dolt version. It does not modify PostgreSQL or start an import. The public clone
|
||||
does not require `dolt login`.
|
||||
|
||||
For a server provisioned before the author-identity check was added, repair the
|
||||
existing clone once with:
|
||||
|
||||
```bash
|
||||
sudo -u deploy -H /usr/local/bin/dolt config --global --add user.name "Signal Platform"
|
||||
sudo -u deploy -H /usr/local/bin/dolt config --global --add user.email "signal-platform@localhost"
|
||||
```
|
||||
|
||||
Do not replace the pinned version with `latest`. A future Dolt upgrade should be
|
||||
a reviewed change to `DOLT_VERSION`, followed by the same provision/check flow.
|
||||
|
||||
## First-run verification
|
||||
|
||||
In Admin → Jobs, wait until no other job is running, then:
|
||||
|
||||
1. Trigger **Dolt Earnings Import**. Expect `completed` with import
|
||||
status `promoted`; a repeat without an upstream change should report `no_op`.
|
||||
2. Trigger **SEC Fundamentals Import**. The first run performs the
|
||||
tracked-universe history backfill and can take materially longer than a daily
|
||||
incremental run. Expect `completed` with import status `promoted`.
|
||||
3. Check Admin → System Events. There should be no new import error.
|
||||
4. Confirm the next-run times correspond to 02:30 and 04:00 New York time.
|
||||
5. Open several ticker pages and confirm the fundamentals panel has populated
|
||||
data and still handles partial/missing issuers cleanly. A ticker held by the
|
||||
quality gate should show **New setups paused** with the specific SEC reason.
|
||||
|
||||
## Verification
|
||||
|
||||
Optional database verification:
|
||||
|
||||
```sql
|
||||
SELECT source, status, revision, source_max_date, started_at, completed_at,
|
||||
validation_json
|
||||
FROM data_import_runs
|
||||
WHERE source IN ('dolt_earnings', 'sec_facts')
|
||||
ORDER BY id DESC
|
||||
LIMIT 10;
|
||||
|
||||
SELECT count(*) FROM earnings_events WHERE source = 'dolt_earnings';
|
||||
SELECT count(*), count(DISTINCT cik) FROM fundamental_snapshots;
|
||||
```
|
||||
|
||||
During the longer first SEC run, execute the following in a second SSH session.
|
||||
It opens an independent database connection and attempts the same source lock:
|
||||
|
||||
```bash
|
||||
cd /opt/signalplatform
|
||||
sudo -u deploy .venv/bin/python - <<'PY'
|
||||
import asyncio
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.database import engine
|
||||
from app.services.data_import import _advisory_key
|
||||
|
||||
|
||||
async def main():
|
||||
key = _advisory_key("sec_facts")
|
||||
async with engine.connect() as connection:
|
||||
acquired = await connection.scalar(
|
||||
text("SELECT pg_try_advisory_lock(:key)"), {"key": key}
|
||||
)
|
||||
print("UNEXPECTED: lock acquired" if acquired else "OK: source lock is busy")
|
||||
if acquired:
|
||||
await connection.execute(
|
||||
text("SELECT pg_advisory_unlock(:key)"), {"key": key}
|
||||
)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
PY
|
||||
```
|
||||
|
||||
Expect `OK: source lock is busy`. This is the remaining live-PostgreSQL
|
||||
mutual-exclusion check; SQLite unit tests cannot exercise PostgreSQL advisory
|
||||
locks. A second Admin trigger should independently report the job as busy.
|
||||
|
||||
## The fundamentals cache
|
||||
|
||||
`fundamental_data` is the compat cache scoring reads. The SEC Fundamentals
|
||||
Import rebuilds it every run from data already in PostgreSQL: newest valid
|
||||
snapshots x latest close for `pe_ratio` and `market_cap`, snapshots alone for
|
||||
`revenue_growth`, and `earnings_events` for `earnings_surprise` and
|
||||
`next_earnings_date`. It therefore also runs after an SEC network/validation
|
||||
failure, a `no_op`, a source-lock skip, or with the job disabled — no network
|
||||
access is involved. The job message appends the cache row count and the changed
|
||||
score-input count.
|
||||
|
||||
A refresh marks affected fundamental and composite score caches stale. The
|
||||
normal 15:30 near-close scanner recomputes them before using the rankings; until
|
||||
then, reads truthfully expose the stale state.
|
||||
|
||||
Verify the refreshed rows:
|
||||
|
||||
```sql
|
||||
SELECT count(*) AS rows,
|
||||
max(fetched_at) AS refreshed_at,
|
||||
count(pe_ratio) AS pe_available,
|
||||
count(revenue_growth) AS growth_available,
|
||||
count(earnings_surprise) AS surprise_available,
|
||||
count(next_earnings_date) AS next_date_available
|
||||
FROM fundamental_data;
|
||||
|
||||
SELECT dimension, is_stale, count(*)
|
||||
FROM dimension_scores
|
||||
WHERE dimension = 'fundamental'
|
||||
GROUP BY dimension, is_stale;
|
||||
```
|
||||
|
||||
## Failure and rollback
|
||||
|
||||
- **There is no provider fallback any more, and no Admin switch that freezes the
|
||||
cache.** Disabling **SEC Fundamentals Import** stops SEC network access only;
|
||||
the 04:00 job still rebuilds `fundamental_data` from the stored snapshots,
|
||||
earnings events and closes.
|
||||
- Restoring `fundamental_data` from the PostgreSQL backup is therefore a
|
||||
*temporary* fix on its own: if the bad values come from the snapshots or from
|
||||
the derivation code, the next scheduled run reproduces them. Fix the cause —
|
||||
restore or repair `fundamental_snapshots` / `earnings_events`, or revert the
|
||||
parser change and re-run `scripts/reparse_fundamentals.py --apply`.
|
||||
- To genuinely freeze the cache while you work, stop the service
|
||||
(`sudo systemctl stop signalplatform.service`) — that stops the scheduler with
|
||||
it. There is no finer-grained control, by design: a silently frozen scoring
|
||||
input is worse than an obvious outage.
|
||||
- Disable a failing source-import job in Admin → Jobs when SEC network access
|
||||
itself must stop. Existing promoted snapshots and events remain available, and
|
||||
the job's runtime message still reports the cache result.
|
||||
- Inspect the job runtime, latest `data_import_runs.validation_json`, service
|
||||
logs, and Admin → System Events before retrying.
|
||||
- `unresolved_filing` is emitted once when a filing enters automatic retry. It
|
||||
does not require a server command. If the gap is still current after 14 days,
|
||||
`filing_gap_aged` is emitted once with the CIK, accession, and parser/mapping
|
||||
reason. A later valid 10-K/10-Q retires the gap even when the original SEC
|
||||
accession never becomes usable.
|
||||
- Successful co-registrant recovery is logged without a warning. New registrants
|
||||
with no XBRL history are also logged quietly, but their ticker page explains
|
||||
that setups remain paused and that successor shells may need `sec_cik_overrides`.
|
||||
- Re-run `sudo -u deploy bash ./deploy/provision_fundamentals.sh --check` for
|
||||
binary, clone, permission, disk, or environment failures.
|
||||
- The Dolt clone is a reproducible cache and does not need a bespoke backup.
|
||||
PostgreSQL (including `earnings_events`, `fundamental_snapshots`, and import
|
||||
audit rows) must remain covered by the normal production database backup.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user