Compare commits

..
69 Commits
Author SHA1 Message Date
Celes Renata 2f2c0d24f6 fix: remove unused columns constant (TS6133) 2026-04-30 03:21:32 +00:00
Celes Renata 861423c1e3 feat: make ticker clickable on positions page — links to company detail
Ticker column now links to /companies/{id} using a ticker→company ID
lookup. Falls back to plain text if company not found.
2026-04-30 03:15:22 +00:00
Celes Renata 13f863ef30 feat: fetch 15-minute bars instead of hourly for intraday prices
Changed intraday_bars default from 1-hour bars to 15-minute bars.
This gives ~26 price points per trading day per ticker (6.5h market
× 4 bars/hour) instead of ~7 hourly bars. Limit raised to 100 to
accommodate the higher bar count.
2026-04-29 23:01:11 +00:00
Celes Renata 2538da3f1e fix: switch market data sources from prev_bars to intraday_bars
The market_api sources were configured with endpoint='prev_bars' which
only fetches a single previous-day bar per ticker. Changed to
'intraday_bars' which fetches hourly bars for today from Polygon's
/v2/aggs/ticker/{ticker}/range/1/hour/{today}/{today} endpoint.

Updated: seed script, beta DB (50 sources), production DB (50 sources).
This gives ~7-8 hourly price bars per trading day per ticker instead
of 1 daily bar.
2026-04-29 22:07:47 +00:00
Celes Renata fa4ad6b15a fix: widen price matching tolerance for sparse market data
Only ~9 price bars per ticker (Polygon returns daily bars, not
intraday). Widened gap tolerance to 6h for intraday, 12h for 1d,
etc. Also skip time-range filtering when price data is sparse
(≤20 bars) to avoid showing no prices at all.
2026-04-29 22:02:23 +00:00
Celes Renata 5109c85a3e fix: remove unused 'hour' variable (TS6133) 2026-04-29 21:48:18 +00:00
Celes Renata 9975c2098b fix: limit X-axis to 8 ticks with date bold + time at angle
Was showing every data point timestamp. Now:
- Recharts generates max 8 evenly-spaced ticks
- Each tick shows 'Apr 29' in bold white + '2 PM' in gray
- All labels at -35° angle to avoid overlap
- Simplified tick component (no hour-boundary filtering needed)
2026-04-29 21:43:44 +00:00
Celes Renata e976363259 ci: retrigger build 2026-04-29 21:34:34 +00:00
Celes Renata b6e2718007 feat: proper time-based X-axis with angled hour labels and bold dates
Replaced string-based X-axis with numeric timestamp axis:
- Custom ChartXTick component renders hour marks at -35° angle
- New day boundaries shown in bold (e.g., 'Apr 29')
- Hour marks shown as '9:00 AM', '10:00 AM' etc.
- Tooltip shows full date+time on hover
- Direction timeline uses formatted timestamps
- Bottom margin increased to accommodate angled labels
2026-04-29 21:26:11 +00:00
Celes Renata cb3eb230d6 fix: fetch trend history per-window and run aggregation 24/7
Two fixes for missing intraday data:

1. Frontend: lifted selectedWindow state to page level so useTrendHistory
   passes window param to the API. Previously fetched all windows with
   limit=500 which exhausted the limit before reaching recent intraday
   data. Now fetches only the selected window's data.

2. Scheduler: removed market-hours-only restriction from periodic
   aggregation. Runs every 15 minutes 24/7 so intraday data is always
   populated for backtesting regardless of market state.
2026-04-29 21:11:46 +00:00
Celes Renata 963a5c462c feat: syntax-highlight decision trace JSON on order detail page
Add lightweight JSON highlighter for the decision trace panel:
- Keys: cyan
- Strings: green
- Numbers: yellow
- Booleans: purple
- Null: red
- Structural chars: gray

SQL explorer already uses Monaco with SQL highlighting — no changes needed there.
2026-04-29 19:33:24 +00:00
Celes Renata 82892b7a3e feat: multi-distro support in deploy-docker.sh
Step 0 now detects the OS and package manager, supporting:
- Debian/Ubuntu (apt)
- RHEL/Rocky/Fedora/CentOS (dnf/yum)
- Arch Linux (pacman)
- openSUSE (zypper)
- WSL (uses host Windows NVIDIA driver, skips driver install)

Handles Docker CE install, NVIDIA driver, NVIDIA Container Toolkit,
and firewall (firewalld + ufw) across all supported distros.
2026-04-29 18:59:40 +00:00
Celes Renata 6f54fd07fa feat: periodic aggregation every 15 minutes during market hours
The aggregation engine only ran when new documents were ingested,
leaving intraday trend data stale for long periods. Now the scheduler
enqueues all 50 tickers for re-aggregation every ~15 minutes during
US market hours (Mon-Fri, 6:30 AM - 1:30 PM PT). This ensures
continuous intraday trend updates based on existing signals and
market price changes.
2026-04-29 18:27:49 +00:00
Celes Renata 99b7dcee98 fix: widen chart time windows for intraday (24h) and 1d (48h)
Intraday was showing only 12h of data (9 sparse points). Widened to
24h to show a full day of intraday trend history. Also widened 1d
from 24h to 48h for better context.
2026-04-29 18:15:54 +00:00
Celes Renata 4f7358f4e3 feat: show current position on company detail trends tab
Displays an 'Open Position' card above the trend charts when we hold
a position in that ticker. Shows shares, avg entry price, current
price, market value, and unrealized P&L with green/red coloring.
Card is hidden when no position exists for the ticker.
2026-04-29 18:06:37 +00:00
Celes Renata 0665cef7e3 fix: set TZ=America/Los_Angeles in Helm config for all pods
Containers default to UTC. The host is PDT but pods don't inherit
the host timezone. Adding TZ to the ConfigMap ensures all services
log and compute timestamps in Pacific time.
2026-04-29 17:53:38 +00:00
Celes Renata 48eca672a9 docs: add TZ environment variable to Helm and Docker docs
Document the TZ config option in both docker-deployment.md and
helm-reference.md. Default is America/Los_Angeles. Frontend uses
the browser's local timezone for display.
2026-04-29 17:50:59 +00:00
Celes Renata f159b20c87 feat: show document title and link in competitive signals panel
Replace raw UUID with a linked document title in both the collapsed
row (using the empty space on the right) and the expanded detail view.
Uses useDocument hook to fetch the title, falls back to truncated UUID
while loading. Clicking the link navigates to the document detail page.
2026-04-29 17:29:26 +00:00
Celes Renata 97fe2249fe fix: extract competitive_signals array from API response wrapper
The /api/patterns/{ticker}/competitive-signals endpoint returns
{competitive_signals: [...], count: N} but the hook was typed as
returning a raw array. The component called .map() on the object,
causing 'e.map is not a function'. Now extracts the array from the
response wrapper.
2026-04-29 17:20:03 +00:00
Celes Renata 951b733ac3 fix: move cutoffTs declaration before its use in filtered
Variable was used before declaration (temporal dead zone error).
Moved windowHours/hoursBack/cutoffTs above the filtered const that
references cutoffTs.
2026-04-29 17:08:36 +00:00
Celes Renata 531e33b0ce fix: company charts X-axis now adjusts to selected window time range
The trend history chart was showing all historical data regardless of
which window was selected — only filtering by window name but not by
time range. Now filters both trend data and price data to the time
range matching the selected window (e.g., 7d shows last 7 days only,
30d shows last 30 days).
2026-04-29 16:59:23 +00:00
Celes Renata 24c753f6e6 fix: debounce ticker search on Trends page to preserve input focus
The TickerFilter triggered a query on every keystroke, causing re-renders
that stole focus from the input. Now uses a local input state with a
300ms debounce before updating the query, keeping focus on the text box
while typing.
2026-04-29 16:54:19 +00:00
Celes Renata 6880f11c26 fix: add /no_think inline tag to disable Qwen3 thinking mode
chat_template_kwargs isn't being respected by the vLLM deployment.
Qwen3 models support /no_think as an inline suffix in the user message
to disable thinking mode. This is the most reliable method across all
serving backends (vLLM, Ollama, SGLang).
2026-04-29 16:11:44 +00:00
Celes Renata eead4f1381 fix: disable thinking mode on vLLM path with chat_template_kwargs
The thesis rewriter uses vLLM (not Ollama) in production. The previous
fix only added think=False to the Ollama payload. For vLLM's
OpenAI-compatible API with Qwen3 models, thinking mode is disabled via
chat_template_kwargs: {enable_thinking: false} in the request body.
2026-04-29 16:04:04 +00:00
Celes Renata 007189c0a5 fix: handle plain-text thinking blocks and disable think mode
The model outputs 'Thinking Process:' as plain text (not in <think> tags).
Updated _strip_thinking_block to handle both XML tags and plain-text
reasoning patterns. Also:
- Added rule 7 to system prompt: 'Do NOT show your thinking process'
- Set think=False in Ollama payload to disable Qwen3 thinking mode
- Added fallback regex to extract thesis from after thinking blocks
2026-04-29 15:50:49 +00:00
Celes Renata f9ee1532dc fix: strip <think> reasoning blocks from thesis LLM output
Qwen3.5 in thinking mode emits <think>...</think> chain-of-thought
before the actual response. The thesis rewriter was returning the raw
output including the entire reasoning block. Now strips thinking tags
from both Ollama and vLLM response paths.
2026-04-29 15:25:04 +00:00
Celes Renata ac29e62033 docs: update equations.md with probabilistic pipeline formulas
Add sections 1B, 2B, 3B, 4B, 5B, 7B covering all new probabilistic
formulas: sigmoid gate, info gain, adaptive decay, regime multiplier,
source accuracy, Bayesian posterior, entropy direction, weighted
disagreement entropy, multiplicative macro exposure, conditional macro
integration, graph-distance attenuation, EW momentum, and EV gate.
Updated constants summary with all new parameters.
2026-04-29 15:12:47 +00:00
Celes Renata 7eecd71a0d ci: retry build (proxy timeout on previous run) 2026-04-29 12:08:15 +00:00
Celes Renata bb40a3cb8e fix: position sync now reconciles — removes positions broker no longer holds
The sync_positions loop only upserted positions from Alpaca but never
deleted DB rows for positions that were closed/liquidated on the broker
side. After a paper reset, the next sync would not remove the stale
positions because they simply weren't in Alpaca's response anymore.

Now performs full reconciliation: after upserting what Alpaca reports,
deletes any DB positions for the account that Alpaca no longer holds.
2026-04-29 12:02:57 +00:00
Celes Renata 4e010bc048 feat: signal math upgrade — probabilistic, regime-aware scoring pipeline
Implement full probabilistic signal processing pipeline gated behind
probabilistic_scoring_enabled feature flag in risk_configs:

- Bayesian log-likelihood accumulator with Beta posterior and entropy
- Regime detector (trend-following, panic, mean-reversion, uncertainty)
- Source accuracy tracker with per-source historical prediction accuracy
- Sigmoid confidence gate replacing binary gate
- Information gain surprise weighting for rare events
- Adaptive recency decay with event-specific half-lives
- Regime multiplier replacing market context multiplier
- Weighted disagreement entropy for contradiction detection
- Multiplicative macro exposure with conditional integration
- Graph-distance attenuated competitive signal propagation
- Exponentially weighted momentum with volatility scaling
- Expected value recommendation gate

All changes backward-compatible: flag=false preserves exact current behavior.
New outputs stored in existing JSONB columns (no schema changes except
source_accuracy table via migration 034).

Tests: 26 property-based tests (14 correctness properties), 99 unit tests,
1789 total tests passing with zero regressions.
2026-04-29 11:41:48 +00:00
Celes Renata 8c3c1aab43 fix: pipeline stop now halts all workers and flushes queues
Workers (ingestion, parser, extractor, aggregation, recommendation,
broker, lake-publisher) now check the pipeline:enabled Redis flag on
each loop iteration and sleep when disabled.

The toggle endpoint flushes all pipeline queues on disable so queued
jobs don't resume when workers eventually check. Broker/trading queues
are excluded from flush to avoid dropping in-flight orders.
2026-04-29 07:59:35 +00:00
Celes Renata cfcfd655e7 fix: reduce max_tokens to 2048 to fit 8192 context window 2026-04-29 06:18:26 +00:00
Celes Renata aaf8cee927 feat: scale extractor to 8 replicas 2026-04-29 05:54:00 +00:00
Celes Renata f264e924f0 fix: thesis rewriter now routes to vLLM when provider is vllm
- thesis_llm.py: add _call_vllm_thesis() using /v1/chat/completions
- thesis_llm.py: check resolved model_provider and route accordingly
- values.yaml: set OLLAMA_BASE_URL to http://10.1.1.12:2701
2026-04-29 05:42:10 +00:00
Celes Renata a36702e5f3 fix: restore REDIS_PASSWORD and MINIO credentials 2026-04-28 22:02:50 -07:00
Celes Renata 01d77c153d fix: set POSTGRES_PASSWORD in core secrets 2026-04-28 21:59:30 -07:00
Celes Renata 8d227b62f6 scale extractor to 4 replicas 2026-04-28 21:54:38 -07:00
Celes Renata b38fb24f14 fix: ensure production uses DB-configured model/provider from UI
- Migration 026: update seed defaults from ollama to vllm/AxionML
- Migration 031: fix existing rows still on old ollama defaults
- Helm values: set OLLAMA_BASE_URL to cluster ollama endpoint (was empty)
- Extractor: guard against switching to ollama when base_url is empty
- OllamaClient: validate base_url on construction to fail fast
2026-04-29 04:33:21 +00:00
Celes Renata 5c64043892 feat: add Rocky 9.7 prerequisites and GPU passthrough for ollama container 2026-04-29 04:16:44 +00:00
Celes Renata 11c6457559 docs: add LLM provider config (Ollama/vLLM/mixed), fix risk network alias in compose 2026-04-29 03:08:54 +00:00
Celes Renata f151747d56 feat: add deploy-docker.sh with auto-detect Ollama, configurable model/URL 2026-04-29 03:03:57 +00:00
Celes Renata 49bff9de50 fix: delete stale trend_evidence before inserting to prevent duplicate accumulation 2026-04-28 19:45:15 +00:00
Celes Renata 27b84fcd2e fix: return open_position_count in trading status for dashboard display 2026-04-28 19:27:40 +00:00
Celes Renata 7e8d518946 feat: add max open positions and position cap controls to trading dashboard 2026-04-28 19:16:50 +00:00
Celes Renata 23f2134754 fix: stop migrations from resetting ai_agents model_name, default to vllm/AxionML/Qwen3.5-9B-NVFP4 2026-04-28 18:58:13 +00:00
Celes Renata 4954318f7b docs: add comprehensive mathematical reference for all pipeline equations 2026-04-28 17:01:03 +00:00
Celes Renata 3b22f5e1fc feat: seed default risk_configs with macro and competitive layers enabled 2026-04-28 16:34:40 +00:00
Celes Renata c188677330 fix: route macro_news documents as macro_event so global event classification runs 2026-04-28 16:18:02 +00:00
Celes Renata 58613955e4 ci: trigger build with secrets configured 2026-04-28 15:21:15 +00:00
Celes Renata b1770f37df ci: trigger build after fixing pipeline config path 2026-04-28 15:18:16 +00:00
Celes Renata 2e4a9b1e08 feat: move Woodpecker server storage to NFS, update OAuth credentials 2026-04-28 15:09:31 +00:00
Celes Renata 416206e37b ci: trigger Woodpecker build 2026-04-28 15:05:19 +00:00
Celes Renata 0a009cdc99 ci: trigger Woodpecker build 2026-04-28 14:49:15 +00:00
Celes Renata 2ab52afc73 ci: trigger Woodpecker build 2026-04-28 14:43:40 +00:00
Celes Renata 1aae36382c fix: point WOODPECKER_GITEA_URL to external https://git.celestium.life 2026-04-28 14:36:48 +00:00
Celes Renata 98bbec9b8d fix: set Gitea ROOT_URL to external domain, update Woodpecker OAuth2 credentials 2026-04-28 14:34:43 +00:00
Celes Renata 24db0e97f6 feat: add Gitea NFS PV, declarative deployment, and wire into runmefirst.sh 2026-04-28 14:29:58 +00:00
Celes Renata 226d799eb2 feat: auto-clamp buy orders to fit within position limits instead of hard-rejecting 2026-04-28 14:20:44 +00:00
Celes Renata e360b66c3e fix: beta trading pipeline — max_tokens default, approval re-enqueue, credentials
- Migration 031: change ai_agents/agent_variants max_tokens default
  from 32768 to 4096 (32768 exceeds vLLM context window, causing
  HTTP 400 on every extraction)
- API: re-enqueue approved orders to broker queue — previously
  approved orders sat in DB with nothing to execute them
- values-beta: enable TRADING_ENABLED, update Alpaca paper keys
2026-04-28 14:13:58 +00:00
Celes Renata 0437943863 fix: reduce vLLM default max_tokens to 4096, update model to AxionML/Qwen3.5-9B-NVFP4
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/push/build-1 Pipeline was successful
ci/woodpecker/push/build-2 Pipeline was successful
ci/woodpecker/push/build-3 Pipeline was successful
ci/woodpecker/push/finalize Pipeline was successful
Build and Push / lint-and-test (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.adapters.broker_adapter name:broker-adapter]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.aggregation.worker name:aggregation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.extractor.worker name:extractor]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.ingestion.worker name:ingestion]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.lake_publisher.worker name:lake-publisher]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.parser.worker name:parser]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.recommendation.worker name:recommendation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.scheduler.app name:scheduler]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.api.app:app --host 0.0.0.0 --port 8000 name:query-api]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.risk.app:app --host 0.0.0.0 --port 8000 name:risk]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000 name:symbol-registry]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.trading.app:app --host 0.0.0.0 --port 8000 name:trading-engine]) (push) Has been cancelled
Build and Push / build-dashboard (push) Has been cancelled
Build and Push / build-superset (push) Has been cancelled
Build and Push / integration-test (push) Has been cancelled
Build and Push / beta-gate (push) Has been cancelled
The model's max_model_len is 16384 — requesting 32768 output tokens
caused HTTP 400 from vLLM. 4096 is a safe default for extraction output.
2026-04-23 19:49:34 +00:00
Celes Renata f7ae34ef3b fix: add extract() method to VLLMClient for extraction pipeline compatibility
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/push/build-3 Pipeline was successful
ci/woodpecker/push/build-1 Pipeline was successful
ci/woodpecker/push/build-2 Pipeline was successful
ci/woodpecker/push/finalize Pipeline was successful
Build and Push / lint-and-test (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.adapters.broker_adapter name:broker-adapter]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.aggregation.worker name:aggregation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.extractor.worker name:extractor]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.ingestion.worker name:ingestion]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.lake_publisher.worker name:lake-publisher]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.parser.worker name:parser]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.recommendation.worker name:recommendation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.scheduler.app name:scheduler]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.api.app:app --host 0.0.0.0 --port 8000 name:query-api]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.risk.app:app --host 0.0.0.0 --port 8000 name:risk]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000 name:symbol-registry]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.trading.app:app --host 0.0.0.0 --port 8000 name:trading-engine]) (push) Has been cancelled
Build and Push / build-dashboard (push) Has been cancelled
Build and Push / build-superset (push) Has been cancelled
Build and Push / integration-test (push) Has been cancelled
Build and Push / beta-gate (push) Has been cancelled
2026-04-23 19:32:33 +00:00
Celes Renata 4bee7a7874 fix: update vLLM model to AxionML/Qwen3.5-9B-NVFP4
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/push/build-3 Pipeline is running
ci/woodpecker/push/build-2 Pipeline failed
ci/woodpecker/push/finalize unknown status
ci/woodpecker/push/build-1 Pipeline failed
Build and Push / lint-and-test (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.adapters.broker_adapter name:broker-adapter]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.aggregation.worker name:aggregation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.extractor.worker name:extractor]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.ingestion.worker name:ingestion]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.lake_publisher.worker name:lake-publisher]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.parser.worker name:parser]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.recommendation.worker name:recommendation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.scheduler.app name:scheduler]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.api.app:app --host 0.0.0.0 --port 8000 name:query-api]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.risk.app:app --host 0.0.0.0 --port 8000 name:risk]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000 name:symbol-registry]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.trading.app:app --host 0.0.0.0 --port 8000 name:trading-engine]) (push) Has been cancelled
Build and Push / build-dashboard (push) Has been cancelled
Build and Push / build-superset (push) Has been cancelled
Build and Push / integration-test (push) Has been cancelled
Build and Push / beta-gate (push) Has been cancelled
2026-04-23 19:30:22 +00:00
Celes Renata 5cf60be76d fix: remove Docker Hub login from CI builds
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/push/build-1 Pipeline was successful
ci/woodpecker/push/build-2 Pipeline was successful
ci/woodpecker/push/build-3 Pipeline was successful
ci/woodpecker/push/finalize Pipeline was successful
Build and Push / lint-and-test (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.adapters.broker_adapter name:broker-adapter]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.aggregation.worker name:aggregation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.extractor.worker name:extractor]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.ingestion.worker name:ingestion]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.lake_publisher.worker name:lake-publisher]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.parser.worker name:parser]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.recommendation.worker name:recommendation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.scheduler.app name:scheduler]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.api.app:app --host 0.0.0.0 --port 8000 name:query-api]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.risk.app:app --host 0.0.0.0 --port 8000 name:risk]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000 name:symbol-registry]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.trading.app:app --host 0.0.0.0 --port 8000 name:trading-engine]) (push) Has been cancelled
Build and Push / build-dashboard (push) Has been cancelled
Build and Push / build-superset (push) Has been cancelled
Build and Push / integration-test (push) Has been cancelled
Build and Push / beta-gate (push) Has been cancelled
Harbor dockerhub-cache proxy handles Docker Hub pulls without
needing direct Docker Hub authentication. Removes the failing
index.docker.io login blocks from all build pipeline steps.
2026-04-23 12:08:37 +00:00
Celes Renata 6909ac5e50 feat: add vLLM config to beta values overlay
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/push/build-3 Pipeline was successful
ci/woodpecker/push/build-1 Pipeline failed
ci/woodpecker/push/build-2 Pipeline was successful
ci/woodpecker/push/finalize unknown status
Build and Push / lint-and-test (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.adapters.broker_adapter name:broker-adapter]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.aggregation.worker name:aggregation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.extractor.worker name:extractor]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.ingestion.worker name:ingestion]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.lake_publisher.worker name:lake-publisher]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.parser.worker name:parser]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.recommendation.worker name:recommendation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.scheduler.app name:scheduler]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.api.app:app --host 0.0.0.0 --port 8000 name:query-api]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.risk.app:app --host 0.0.0.0 --port 8000 name:risk]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000 name:symbol-registry]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.trading.app:app --host 0.0.0.0 --port 8000 name:trading-engine]) (push) Has been cancelled
Build and Push / build-dashboard (push) Has been cancelled
Build and Push / build-superset (push) Has been cancelled
Build and Push / integration-test (push) Has been cancelled
Build and Push / beta-gate (push) Has been cancelled
2026-04-23 08:19:03 +00:00
Celes Renata 117b693b19 feat: add remote vLLM support with provider abstraction layer
ci/woodpecker/push/test Pipeline failed
ci/woodpecker/push/build-1 unknown status
ci/woodpecker/push/build-3 unknown status
ci/woodpecker/push/build-2 unknown status
ci/woodpecker/push/finalize unknown status
Build and Push / lint-and-test (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.adapters.broker_adapter name:broker-adapter]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.aggregation.worker name:aggregation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.extractor.worker name:extractor]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.ingestion.worker name:ingestion]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.lake_publisher.worker name:lake-publisher]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.parser.worker name:parser]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.recommendation.worker name:recommendation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.scheduler.app name:scheduler]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.api.app:app --host 0.0.0.0 --port 8000 name:query-api]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.risk.app:app --host 0.0.0.0 --port 8000 name:risk]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000 name:symbol-registry]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.trading.app:app --host 0.0.0.0 --port 8000 name:trading-engine]) (push) Has been cancelled
Build and Push / build-dashboard (push) Has been cancelled
Build and Push / build-superset (push) Has been cancelled
Build and Push / integration-test (push) Has been cancelled
Build and Push / beta-gate (push) Has been cancelled
- LLMClient Protocol for provider-agnostic inference
- VLLMClient for OpenAI-compatible /v1/chat/completions API
- LLM client factory with provider routing (ollama/vllm)
- VLLMConfig with VLLM_* environment variable loading
- Updated extractor worker with health check and provider switching
- Updated event classifier to use LLMClient protocol
- Helm values for vLLM configuration
- 18 unit tests + 6 property-based tests
- Full backward compatibility preserved
2026-04-23 08:17:23 +00:00
Celes Renata 63e4fb96ea fix: increase waitFor timeout for CI environments
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/push/build-3 Pipeline was successful
ci/woodpecker/push/build-1 Pipeline was successful
ci/woodpecker/push/build-2 Pipeline was successful
ci/woodpecker/push/finalize Pipeline was successful
Build and Push / lint-and-test (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.adapters.broker_adapter name:broker-adapter]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.aggregation.worker name:aggregation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.extractor.worker name:extractor]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.ingestion.worker name:ingestion]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.lake_publisher.worker name:lake-publisher]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.parser.worker name:parser]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.recommendation.worker name:recommendation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.scheduler.app name:scheduler]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.api.app:app --host 0.0.0.0 --port 8000 name:query-api]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.risk.app:app --host 0.0.0.0 --port 8000 name:risk]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000 name:symbol-registry]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.trading.app:app --host 0.0.0.0 --port 8000 name:trading-engine]) (push) Has been cancelled
Build and Push / build-dashboard (push) Has been cancelled
Build and Push / build-superset (push) Has been cancelled
Build and Push / integration-test (push) Has been cancelled
Build and Push / beta-gate (push) Has been cancelled
2026-04-22 03:36:36 +00:00
Celes Renata e517cea081 ci: retrigger pipeline
ci/woodpecker/push/test Pipeline failed
ci/woodpecker/push/build-2 unknown status
ci/woodpecker/push/build-3 unknown status
ci/woodpecker/push/build-1 unknown status
ci/woodpecker/push/finalize unknown status
Build and Push / lint-and-test (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.adapters.broker_adapter name:broker-adapter]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.aggregation.worker name:aggregation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.extractor.worker name:extractor]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.ingestion.worker name:ingestion]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.lake_publisher.worker name:lake-publisher]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.parser.worker name:parser]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.recommendation.worker name:recommendation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.scheduler.app name:scheduler]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.api.app:app --host 0.0.0.0 --port 8000 name:query-api]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.risk.app:app --host 0.0.0.0 --port 8000 name:risk]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000 name:symbol-registry]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.trading.app:app --host 0.0.0.0 --port 8000 name:trading-engine]) (push) Has been cancelled
Build and Push / build-dashboard (push) Has been cancelled
Build and Push / build-superset (push) Has been cancelled
Build and Push / integration-test (push) Has been cancelled
Build and Push / beta-gate (push) Has been cancelled
2026-04-22 03:23:14 +00:00
Celes Renata 88ad1e8d99 feat: comprehensive docs, unit tests, docker-compose app services
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/push/build-3 Pipeline was successful
ci/woodpecker/push/build-2 Pipeline failed
ci/woodpecker/push/finalize unknown status
ci/woodpecker/push/build-1 Pipeline failed
Build and Push / lint-and-test (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.adapters.broker_adapter name:broker-adapter]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.aggregation.worker name:aggregation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.extractor.worker name:extractor]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.ingestion.worker name:ingestion]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.lake_publisher.worker name:lake-publisher]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.parser.worker name:parser]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.recommendation.worker name:recommendation]) (push) Has been cancelled
Build and Push / build-services (map[cmd:python -m services.scheduler.app name:scheduler]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.api.app:app --host 0.0.0.0 --port 8000 name:query-api]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.risk.app:app --host 0.0.0.0 --port 8000 name:risk]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000 name:symbol-registry]) (push) Has been cancelled
Build and Push / build-services (map[cmd:uvicorn services.trading.app:app --host 0.0.0.0 --port 8000 name:trading-engine]) (push) Has been cancelled
Build and Push / build-dashboard (push) Has been cancelled
Build and Push / build-superset (push) Has been cancelled
Build and Push / integration-test (push) Has been cancelled
Build and Push / beta-gate (push) Has been cancelled
- Add scheduler and ingestion unit tests (test_scheduler_unit.py, test_ingestion_unit.py)
- Add all 13 app services + dashboard to docker-compose.yml
- Add full documentation suite: API reference, Helm reference, Docker deployment guide,
  3 architecture diagrams (K8s, Docker Compose, data pipeline), AI agent guide,
  backup/restore guide, observability/metrics reference, per-service docs
- Add intelligence pipeline deep-dive docs with Mermaid diagrams
- Update README with documentation index and links
- Add specs for comprehensive-quality-docs, intelligence-pipeline-deep-dive,
  sanitized-pipeline-docs
2026-04-22 02:56:41 +00:00
Celes Renata f251c53f92 fix: risk engine blocking sell orders on over-concentrated positions
Two bugs: (1) trading engine omitted estimated_value from sell order
jobs, causing risk engine to compute 0 reduction; (2) risk engine
applied position size limits to sells, trapping users in positions
they couldn't exit. Sells now always pass position value/pct checks.
2026-04-22 02:07:24 +00:00
139 changed files with 23951 additions and 442 deletions
@@ -0,0 +1 @@
{"specId": "e433350c-baf0-4f4f-a30e-3724f6654090", "workflowType": "requirements-first", "specType": "feature"}
@@ -0,0 +1,377 @@
# Design Document: Comprehensive Quality & Documentation
## Overview
This design covers three pillars for the Stonks Oracle platform:
1. **Test Coverage** — Close unit test gaps in the scheduler and ingestion services, fix pre-existing test failures in the extractor module, and achieve a fully green test suite (Requirements 14).
2. **Docker Deployment** — Extend `docker-compose.yml` to include all 13 application services plus the frontend, enabling full-platform local development without Kubernetes (Requirement 5).
3. **Documentation** — Produce comprehensive documentation covering per-service features, API references, Helm chart configuration, Docker deployment, three Mermaid architecture diagrams, AI agent building, backup/restore, observability, and README resource links (Requirements 616).
### Design Rationale
The platform has mature production code across 13 services but uneven test coverage and documentation. The scheduler and ingestion services lack dedicated unit tests — their logic is only exercised through integration tests. Four extractor-related test files have pre-existing failures that block CI. Documentation exists only as a local dev setup guide, a pipeline overview, and a runbook. This initiative fills those gaps systematically.
The approach prioritizes:
- **Test isolation**: Mock all external dependencies (PostgreSQL, Redis, MinIO, Ollama) so unit tests run fast and deterministically.
- **Documentation from source**: Generate API references by inspecting actual FastAPI route definitions, Helm values from `values.yaml`, and metrics from `services/shared/metrics.py`.
- **Docker parity with Kubernetes**: Mirror the Helm chart's service definitions in Docker Compose so both deployment modes stay in sync.
## Architecture
The work does not change the platform's runtime architecture. It adds:
1. **New test files** in `tests/` for scheduler and ingestion unit tests.
2. **Fixes** to existing test files and/or production code to resolve failures.
3. **New service definitions** in `docker-compose.yml` using the existing `docker/Dockerfile` with `SERVICE_CMD` build args.
4. **New documentation files** in `docs/` organized by topic.
5. **Updated `README.md`** with a documentation index and Mermaid diagram.
```mermaid
graph TD
subgraph "Test Coverage (Reqs 1-4)"
T1[tests/test_scheduler_unit.py]
T2[tests/test_ingestion_unit.py]
T3[Fix test_extractor_prompts.py]
T4[Fix test_extractor_schemas.py]
T5[Fix test_ollama_client.py]
T6[Fix test_filings_adapter.py]
end
subgraph "Docker (Req 5)"
D1[docker-compose.yml<br/>+ 13 app services + frontend]
end
subgraph "Documentation (Reqs 6-16)"
DOC1[docs/services.md]
DOC2[docs/api-reference.md]
DOC3[docs/helm-reference.md]
DOC4[docs/docker-deployment.md]
DOC5[docs/architecture-kubernetes.md]
DOC6[docs/architecture-docker-compose.md]
DOC7[docs/architecture-data-pipeline.md]
DOC8[docs/ai-agents.md]
DOC9[docs/backup-restore.md]
DOC10[docs/observability.md]
DOC11[README.md update]
end
```
## Components and Interfaces
### 1. Scheduler Unit Tests (Requirement 1)
**Target module**: `services/scheduler/app.py`
**Functions to test in isolation**:
- `get_cadence_for_source(source_type, config)` — Returns polling interval from config or defaults.
- `compute_backoff(retry_count)` — Exponential backoff with cap.
- `is_source_due(...)` — Core scheduling logic: determines if a source needs polling based on last run status, timing, retry state.
- `build_job_payload(source, aliases, now)` — Constructs the ingestion job dict.
- `schedule_cycle(pool, rds)` — Full scheduling pass (mocked DB/Redis).
- `check_rate_limit(rds, source_type, now)` — Rate limiting with per-type and global Polygon limits.
- `recover_stale_documents(pool, rds)` — Re-enqueue orphaned parsed documents.
- `retry_failed_extractions(pool, rds)` — Re-enqueue failed extractions.
**Mocking strategy**:
- `asyncpg.Pool``AsyncMock` with `.fetch()`, `.fetchrow()`, `.fetchval()`, `.execute()` returning canned records.
- `redis.asyncio.Redis``AsyncMock` with `.rpush()`, `.set()`, `.get()`, `.incr()`, `.expire()`, `.decr()`, `.delete()` tracking calls.
- Use `unittest.mock.patch` for module-level imports where needed.
**Test file**: `tests/test_scheduler_unit.py`
### 2. Ingestion Unit Tests (Requirement 2)
**Target module**: `services/ingestion/worker.py`
**Functions to test**:
- `process_job(job, pool, rds, minio_client, adapters)` — Main job processing with various adapter outcomes.
- Error handling paths: adapter returns `AdapterResult(error=...)`, retry exhaustion, dead-letter routing.
- Deduplication: content hash already seen in Redis, cross-source document dedup via `dedupe_items`.
**Mocking strategy**:
- Adapters → `AsyncMock` returning `AdapterResult` with controlled `error`, `items`, `content_hash`, `raw_payload`.
- `asyncpg.Pool``AsyncMock` for `ingestion_runs` INSERT/UPDATE, `persist_ingestion_items`, `record_retrieval_failure`.
- `redis.asyncio.Redis``AsyncMock` for dedupe checks, queue pushes, DLQ routing.
- `minio.Minio``MagicMock` for `upload_raw_artifact`.
**Test file**: `tests/test_ingestion_unit.py`
### 3. Extractor Test Fixes (Requirement 3)
**Target files**:
- `tests/test_extractor_prompts.py`
- `tests/test_extractor_schemas.py`
- `tests/test_ollama_client.py`
- `tests/test_filings_adapter.py`
**Approach**: Run each file individually, diagnose failures, and fix either the test setup (mock configuration, fixture data) or the production code. Preserve original test intent and assertions. If production code changes are needed, add regression tests.
### 4. Full Test Suite Green (Requirement 4)
**Verification**: Run `pytest tests/ -x --tb=short -q` and `ruff check services/` after all fixes. All existing `test_pbt_*` files must remain passing. Any production code fix must include a regression test.
### 5. Docker Compose Application Services (Requirement 5)
**Current state**: `docker-compose.yml` defines 7 infrastructure services (postgres, redis, minio, minio-init, ollama, trino, hive-metastore, superset).
**Addition**: 14 new service definitions (13 app services + frontend dashboard):
| Service | Image Build | Command | Port | Depends On |
|---------|------------|---------|------|------------|
| scheduler | `docker/Dockerfile.scheduler` | `python -m services.scheduler.app` | — | postgres, redis |
| symbol-registry | `docker/Dockerfile` | `uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000` | 8001:8000 | postgres |
| ingestion | `docker/Dockerfile` | `python -m services.ingestion.worker` | — | postgres, redis, minio |
| parser | `docker/Dockerfile` | `python -m services.parser.worker` | — | postgres, redis |
| extractor | `docker/Dockerfile` | `python -m services.extractor.main` | — | postgres, redis, ollama |
| aggregation | `docker/Dockerfile` | `python -m services.aggregation.main` | — | postgres, redis |
| recommendation | `docker/Dockerfile` | `python -m services.recommendation.main` | — | postgres, redis |
| trading-engine | `docker/Dockerfile` | `uvicorn services.trading.app:app --host 0.0.0.0 --port 8000` | 8002:8000 | postgres, redis |
| risk-engine | `docker/Dockerfile` | `uvicorn services.risk.app:app --host 0.0.0.0 --port 8000` | 8003:8000 | postgres |
| broker-adapter | `docker/Dockerfile` | `python -m services.adapters.broker_service` | — | postgres, redis |
| lake-publisher | `docker/Dockerfile` | `python -m services.lake_publisher.jobs` | — | postgres, minio |
| query-api | `docker/Dockerfile` | `uvicorn services.api.app:app --host 0.0.0.0 --port 8000` | 8004:8000 | postgres, redis, minio |
| dashboard | `frontend/Dockerfile` | nginx (built-in) | 3000:8080 | query-api |
**Common environment block** (shared via `x-app-env` YAML anchor):
```yaml
POSTGRES_HOST: postgres
POSTGRES_PORT: "5432"
POSTGRES_DB: stonks
POSTGRES_USER: stonks
POSTGRES_PASSWORD: stonks_dev
REDIS_HOST: redis
REDIS_PORT: "6379"
MINIO_ENDPOINT: minio:9000
MINIO_ACCESS_KEY: minioadmin
MINIO_SECRET_KEY: minioadmin
OLLAMA_BASE_URL: http://ollama:11434
```
**`.env` file support**: `MARKET_DATA_API_KEY`, `BROKER_API_KEY`, `BROKER_API_SECRET`, `BROKER_BASE_URL` loaded via `env_file: .env` on services that need them (ingestion, broker-adapter, trading-engine).
**Health checks**: FastAPI services use `curl -f http://localhost:8000/health`; workers use process liveness checks. Infrastructure `depends_on` uses `condition: service_healthy`.
### 6. Documentation Structure (Requirements 616)
All documentation files are Markdown in `docs/`. The structure:
```
docs/
├── services.md # Req 6: Per-service feature docs
├── api-reference.md # Req 7: All 4 FastAPI API references
├── helm-reference.md # Req 8: Helm chart values reference
├── docker-deployment.md # Req 9: Docker deployment guide
├── architecture-kubernetes.md # Req 10: K8s Mermaid diagram
├── architecture-docker-compose.md # Req 11: Docker Compose Mermaid diagram
├── architecture-data-pipeline.md # Req 12: Data pipeline Mermaid diagram
├── ai-agents.md # Req 13: AI agent building guide
├── backup-restore.md # Req 14: Backup and restore guide
├── observability.md # Req 15: Observability & metrics reference
├── LOCAL_DEV_SETUP.md # (existing)
├── llm-to-trade-pipeline.md # (existing)
└── notes/
└── runbook.md # (existing)
```
#### 6a. Service Feature Documentation (`docs/services.md`) — Req 6
For each of the 13 services, document:
- **Purpose**: What the service does in the pipeline.
- **Entry point**: Module path (e.g., `services.scheduler.app`).
- **Configuration**: Environment variables from `services/shared/config.py` relevant to this service.
- **Database tables**: Tables read/written by this service.
- **Redis queues**: Queue names consumed from and published to (from `services/shared/redis_keys.py`).
- **Queue message schema**: JSON structure of messages.
- **Signal layers**: For aggregation/recommendation, document the three signal layers (company, macro, competitive), their toggles (`macro_enabled`, `competitive_enabled` in `risk_configs`), and weight configurations.
- **Trading engine features**: For the trading service, document position sizing, circuit breakers, reserve pool, risk tier auto-adjustment, backtesting, and notification configuration.
Queue topology reference (from `redis_keys.py`):
| Queue | Producer | Consumer |
|-------|----------|----------|
| `stonks:queue:ingestion` | scheduler | ingestion |
| `stonks:queue:parsing` | ingestion | parser |
| `stonks:queue:extraction` | parser | extractor |
| `stonks:queue:macro_classification` | parser, scheduler | extractor |
| `stonks:queue:aggregation` | extractor | aggregation |
| `stonks:queue:recommendation` | aggregation | recommendation |
| `stonks:queue:lake_publish` | various | lake-publisher |
| `stonks:queue:broker_orders` | trading-engine, trading API | broker-adapter |
| `stonks:queue:trading_decisions` | recommendation | trading-engine |
#### 6b. API Reference (`docs/api-reference.md`) — Req 7
Document all endpoints from the four FastAPI services by inspecting their route definitions:
**Query API** (`services/api/app.py`): ~40+ endpoints covering companies, documents, trends, recommendations, evidence drill-down, orders, positions, portfolio, global events, macro impacts, competitive signals, trend projections, agents, dead-letter queues, pipeline control, SQL explorer, saved queries, audit trail, DevOps metrics, and Prometheus metrics.
**Symbol Registry API** (`services/symbol_registry/app.py`): Companies CRUD, aliases, watchlists, sources, exposure profiles, competitor relationships, competitor inference.
**Trading API** (`services/trading/app.py`): Health/readiness, engine status, config update, pause/resume, reset, decisions audit, performance metrics/history, backtesting, notifications config/history, override orders, debug state.
**Risk API** (`services/risk/app.py`): Order evaluation (`POST /evaluate`), health, pending approvals, approval review, approval expiration.
For each endpoint: method, path, query parameters (type, default, constraints), request body schema, response schema, error codes (4xx/5xx).
#### 6c. Helm Chart Reference (`docs/helm-reference.md`) — Req 8
Document from `infra/helm/stonks-oracle/values.yaml`:
- `image` block: registry, pullPolicy, tag
- `pipelineEnabled`: toggle and effect on worker replicas
- `services` block: per-service structure (replicas, image, command, tier, port, secrets, resources, probes)
- `config` block: all ConfigMap environment variables with defaults and descriptions
- `secrets` block: core, broker, market, gmail, dashboard — injection via `--set` flags
- `ingress` block: className, clusterIssuer, host mappings
- Analytics stack: trino, hiveMetastore, superset toggles and resources
- `networkPolicies.enabled`: default-deny-ingress behavior
- Value override files: `values-beta.yaml`, `values-paper.yaml` and their deployment stages
#### 6d. Docker Deployment Guide (`docs/docker-deployment.md`) — Req 9
- Complete service inventory with images, ports, volumes, environment variables
- `.env` file format with all required/optional variables
- Volume mounts and data persistence (pgdata, miniodata, ollama_models, hive_data, superset_data)
- Health check configurations
- Dockerfile build arguments (`SERVICE_CMD`)
- Operational commands: start, stop, restart, logs, scale, reset (`docker compose down -v`)
#### 6e. Architecture Diagrams (Reqs 1012)
**Kubernetes diagram** (`docs/architecture-kubernetes.md`):
- `stonks-oracle` namespace with all 13 services grouped by tier (api, processing, trading, orchestration, analytics, frontend)
- External cluster services in their namespaces (postgresql-service, redis-service, minio-service, ollama-service)
- Traefik ingress routes to external domains
- Network policy boundaries
- Analytics plane (Trino, Hive Metastore, Superset)
- Helm-managed secrets (core, broker, market, gmail) with consumer mapping
- Service tier distinction (API with ingress, pipeline workers, trading)
**Docker Compose diagram** (`docs/architecture-docker-compose.md`):
- All infrastructure + application containers
- Host port mappings
- `depends_on` relationships and health check dependencies
- Named volumes and mount points
- `.env` file providing API keys
- Internal Docker network connectivity
**Data Pipeline diagram** (`docs/architecture-data-pipeline.md`):
- External sources → ingestion → parsing → extraction → aggregation → recommendation → risk → trading → broker
- Redis queue topology with queue names
- Three signal layers as distinct paths merging at aggregation
- Data stores at each stage (MinIO, PostgreSQL, Redis)
- Trading engine decision loop
- Analytical branch (lake publisher → MinIO/Parquet → Trino → Superset/Dashboard)
- External integrations (Ollama, Alpaca, AWS SNS, Gmail)
#### 6f. AI Agent Guide (`docs/ai-agents.md`) — Req 13
- Three built-in agents: document-extractor, event-classifier, thesis-rewriter
- Per-agent: purpose, input data, output schema, default model, system prompt structure, user prompt template
- `ai_agents` table schema and registration (system-seeded vs API-created)
- `agent_variants` table: create, activate, deactivate variants for A/B testing
- `AgentConfigResolver` module: TTL cache (60s default), COALESCE-based variant override, fallback behavior
- Performance logging: `agent_performance_log` table, querying for variant comparison
- API endpoints: CRUD on `/api/agents`, test endpoint `/api/agents/{id}/test`
- Step-by-step guide: creating a new variant with different model/prompt and activating it
#### 6g. Backup & Restore Guide (`docs/backup-restore.md`) — Req 14
Scripts in `scripts/`:
- `backup-db.sh`: PostgreSQL dump, CLI args, storage location, retention (keeps last 7)
- `restore-db.sh`: PostgreSQL restore, service scale-down/up, data loss implications
- `backup-redis.sh`: Redis RDB snapshot backup
- `backup.sh`: Combined backup (DB + Redis), `--upload-minio` option
- `restore.sh`: Combined restore
- Full nuke-and-rebuild procedure (connection termination, DB drop, Redis flush, redeploy, re-seed)
- Recommended backup schedules and automation (cron, Kubernetes CronJobs)
#### 6h. Observability Reference (`docs/observability.md`) — Req 15
- `/metrics` endpoint on query-api, Prometheus scrape configuration
- All metrics from `services/shared/metrics.py`:
- **Ingestion**: `stonks_ingestion_jobs_total`, `stonks_ingestion_items_fetched_total`, `stonks_ingestion_items_new_total`, `stonks_ingestion_items_deduped_total`, `stonks_ingestion_errors_total`, `stonks_ingestion_adapter_duration_seconds`
- **Parsing**: `stonks_parse_jobs_total`, `stonks_parse_quality_score`, `stonks_parse_low_quality_total`, `stonks_parse_duration_seconds`
- **Extraction**: `stonks_extraction_jobs_total`, `stonks_extraction_attempts_total`, `stonks_extraction_retries_total`, `stonks_extraction_duration_seconds`, `stonks_extraction_confidence`, `stonks_extraction_validation_errors_total`, `stonks_extraction_tokens_total`
- **Aggregation**: `stonks_aggregation_windows_total`, `stonks_aggregation_signals_total`, `stonks_aggregation_contradiction_score`, `stonks_aggregation_duration_seconds`
- **Recommendation**: `stonks_recommendations_total`, `stonks_recommendations_suppressed_total`, `stonks_recommendation_confidence`
- **Lake**: `stonks_lake_facts_published_total`, `stonks_lake_publish_duration_seconds`, `stonks_lake_publish_errors_total`, `stonks_lake_publish_bytes_total`
- **Trading**: `stonks_orders_submitted_total`, `stonks_orders_rejected_total`, `stonks_orders_filled_total`, `stonks_orders_duplicates_prevented_total`, `stonks_risk_evaluations_total`, `stonks_risk_check_failures_total`, `stonks_positions_synced_total`
- **Alerting**: `stonks_alerts_fired_total`, `stonks_alerts_resolved_total`, `stonks_alert_check_duration_seconds`, `stonks_alert_active`
- **DLQ**: `stonks_dlq_items_total`, `stonks_dlq_replayed_total`, `stonks_dlq_depth`
- **Active**: `stonks_active_jobs`
- Alerting module (`services/shared/alerting.py`): 4 alert rules (source_failures, schema_failure_spike, analytical_lag, broker_issues), thresholds, evaluation windows, ConfigMap variables
- Structured JSON logging format, trace context (trace_id, span_id)
- Dead-letter queue system: queue names (`stonks:dlq:<queue>`), routing, replay tooling
- Recommended Prometheus/Grafana queries
#### 6i. README Update — Req 16
- Add "Documentation" section with links to all docs
- Replace ASCII architecture diagram with Mermaid or link to diagram docs
- Preserve all existing content (license, features, tech stack, project structure, deployment)
## Data Models
No new database tables or schema changes are introduced. This initiative works with existing tables:
**Tables referenced in test coverage work**:
- `sources`, `companies`, `company_aliases` — scheduler source polling
- `ingestion_runs` — scheduler run tracking, ingestion job recording
- `documents`, `document_company_mentions` — ingestion persistence, stale document recovery
- `document_intelligence`, `document_impact_records` — extractor test fixtures
- `model_performance_metrics` — extractor schema validation metrics
**Tables documented** (not modified):
- All tables listed above plus `trend_windows`, `trend_history`, `trend_projections`, `recommendations`, `recommendation_evidence`, `risk_evaluations`, `orders`, `order_events`, `positions`, `portfolio_snapshots`, `trading_decisions`, `circuit_breaker_events`, `reserve_pool_ledger`, `risk_tier_history`, `backtest_runs`, `backtest_trades`, `notifications`, `global_events`, `macro_impact_records`, `exposure_profiles`, `competitor_relationships`, `competitive_signal_records`, `ai_agents`, `agent_variants`, `agent_performance_log`, `audit_events`, `watchlists`, `watchlist_members`, `retention_policies`, `market_snapshots`
## Error Handling
### Test Coverage
- **Mock failures**: Unit tests must verify that scheduler and ingestion services handle database/Redis connection failures gracefully (no crashes, proper logging).
- **Adapter errors**: Ingestion unit tests must verify retry logic with exponential backoff and dead-letter queue routing after retry exhaustion.
- **Test fix approach**: When fixing pre-existing failures, prefer fixing test setup over changing production code. If production code changes are needed, add regression tests to prevent re-introduction.
### Docker Compose
- **Health check failures**: Application services use `depends_on` with `condition: service_healthy` to wait for infrastructure. Health checks have `interval`, `timeout`, `retries`, and `start_period` configured.
- **Missing `.env` file**: Services that need API keys (ingestion, broker-adapter, trading-engine) will start but log warnings about missing keys. The platform runs in a degraded mode without external API access.
- **Build failures**: Each service uses the same base Dockerfile with `SERVICE_CMD` build arg. Build errors are isolated per service.
### Documentation
- **Stale documentation**: Documentation is generated from source code inspection. If the codebase changes after documentation is written, the docs may drift. The README links section serves as a single index to find and update docs.
- **Diagram accuracy**: Mermaid diagrams are hand-authored based on current architecture. They should be updated when services are added or removed.
## Testing Strategy
### PBT Applicability Assessment
Property-based testing is **NOT applicable** to this feature. The work consists of:
1. **Unit tests for existing services** — These are example-based tests with mocked dependencies, not pure functions with universal properties.
2. **Fixing pre-existing test failures** — Bug fixes to existing tests/code.
3. **Docker Compose configuration** — Declarative infrastructure configuration.
4. **Documentation** — Markdown files with no executable logic.
None of these involve new pure functions, parsers, serializers, or business logic where PBT would add value. The existing `test_pbt_*` files (22 files covering trading, aggregation, competitive intelligence, etc.) already provide PBT coverage for the platform's core logic and must remain passing.
### Unit Testing Strategy
**New test files**:
- `tests/test_scheduler_unit.py` — 8+ test cases covering all scheduler pure functions and the `schedule_cycle` orchestration with mocked dependencies.
- `tests/test_ingestion_unit.py` — 6+ test cases covering adapter error handling, retry logic, deduplication, and dead-letter queue routing.
**Test fix files** (existing, to be repaired):
- `tests/test_extractor_prompts.py`
- `tests/test_extractor_schemas.py`
- `tests/test_ollama_client.py`
- `tests/test_filings_adapter.py`
**Test framework**: pytest + pytest-asyncio (already configured in the project).
**Mocking approach**: `unittest.mock.AsyncMock` for async dependencies, `unittest.mock.MagicMock` for sync dependencies, `unittest.mock.patch` for module-level state.
### Verification Criteria
1. `pytest tests/ -x --tb=short -q` → zero failures
2. `ruff check services/` → zero violations
3. All 22 existing `test_pbt_*` files pass unchanged
4. `docker compose config` validates the updated docker-compose.yml
5. All documentation files render valid Markdown with working internal links
@@ -0,0 +1,236 @@
# Requirements Document
## Introduction
This initiative covers three pillars for the Stonks Oracle platform: (1) closing unit test coverage gaps across all 13 services, fixing pre-existing test failures, and ensuring every feature has proper automated tests; (2) updating the Docker Compose deployment to include all application services so users can run the full platform without Kubernetes; and (3) producing comprehensive documentation covering every feature, all API endpoints, Helm chart configuration, Docker deployment options, and three Mermaid architecture diagrams (Kubernetes deployment, Docker Compose deployment, and data pipeline), with the README updated to link to all resources.
## Glossary
- **Test_Suite**: The collection of pytest unit tests, property-based tests, and integration tests in the `tests/` directory
- **Docker_Compose_Stack**: The `docker-compose.yml` file and associated Dockerfiles that define the local development environment
- **Helm_Chart**: The Kubernetes deployment configuration at `infra/helm/stonks-oracle/` including `values.yaml`, value overrides, and templates
- **Query_API**: The FastAPI REST service at `services/api/app.py` serving analytics and dashboard queries
- **Symbol_Registry_API**: The FastAPI REST service at `services/symbol_registry/app.py` managing companies, watchlists, sources, exposure profiles, and competitor relationships
- **Trading_API**: The FastAPI REST service at `services/trading/app.py` controlling the autonomous trading engine
- **Risk_API**: The FastAPI REST service at `services/risk/app.py` evaluating order risk and managing approval workflows
- **Scheduler_Service**: The service at `services/scheduler/` that triggers ingestion cycles on a cadence
- **Ingestion_Service**: The queue worker at `services/ingestion/` that fetches market data, news, filings, and macro events
- **Extractor_Service**: The queue worker at `services/extractor/` that performs LLM-based intelligence extraction and event classification
- **Documentation_Set**: The collection of Markdown files in `docs/` that describe features, APIs, deployment, and architecture
- **Architecture_Diagram**: A Mermaid-syntax diagram showing services, data stores, external integrations, and data flow. Three diagrams are produced: Kubernetes deployment, Docker Compose deployment, and data pipeline
- **README**: The root `README.md` file serving as the project entry point
## Requirements
### Requirement 1: Scheduler Service Unit Tests
**User Story:** As a developer, I want the scheduler service to have dedicated unit tests, so that scheduling logic, cadence management, and source polling behavior are verified independently of integration tests.
#### Acceptance Criteria
1. WHEN the Test_Suite is executed for the scheduler module, THE Test_Suite SHALL include unit tests covering job enqueue logic, polling interval calculation, and source due-date evaluation
2. WHEN a scheduler unit test is run, THE Test_Suite SHALL mock all external dependencies (PostgreSQL, Redis) and test scheduling logic in isolation
3. THE Test_Suite SHALL verify that the scheduler correctly enqueues ingestion jobs for sources whose polling interval has elapsed
4. IF a database or Redis connection fails during scheduling, THEN THE Test_Suite SHALL verify that the Scheduler_Service handles the error without crashing
### Requirement 2: Ingestion Service Unit Tests
**User Story:** As a developer, I want the ingestion service to have unit tests for adapter error handling and retry logic, so that data fetching resilience is verified beyond integration tests.
#### Acceptance Criteria
1. WHEN the Test_Suite is executed for the ingestion module, THE Test_Suite SHALL include unit tests covering adapter error handling, retry logic, and deduplication behavior
2. WHEN an external API returns an error response, THE Test_Suite SHALL verify that the Ingestion_Service retries according to the configured backoff policy
3. WHEN a duplicate content hash is detected, THE Test_Suite SHALL verify that the Ingestion_Service skips re-processing the document
4. IF all retry attempts are exhausted, THEN THE Test_Suite SHALL verify that the Ingestion_Service routes the failed job to the dead-letter queue
### Requirement 3: Extractor Test Failure Fixes
**User Story:** As a developer, I want the pre-existing test failures in the extractor module to be resolved, so that the full test suite passes cleanly in CI.
#### Acceptance Criteria
1. WHEN the Test_Suite is executed, THE Test_Suite SHALL pass all tests in `test_extractor_prompts.py` without failures
2. WHEN the Test_Suite is executed, THE Test_Suite SHALL pass all tests in `test_extractor_schemas.py` without failures
3. WHEN the Test_Suite is executed, THE Test_Suite SHALL pass all tests in `test_ollama_client.py` without failures
4. WHEN the Test_Suite is executed, THE Test_Suite SHALL pass all tests in `test_filings_adapter.py` without failures
5. THE Test_Suite SHALL maintain the original test intent and assertions when fixing failures, modifying only the code under test or test setup as needed
### Requirement 4: Full Test Suite Green Status
**User Story:** As a developer, I want the entire test suite to pass, so that CI builds succeed and regressions are caught immediately.
#### Acceptance Criteria
1. WHEN `pytest tests/ -x --tb=short -q` is executed, THE Test_Suite SHALL report zero failures across all test files
2. WHEN `ruff check services/` is executed, THE Test_Suite SHALL report zero lint violations
3. THE Test_Suite SHALL maintain all existing property-based tests (files prefixed `test_pbt_*`) in a passing state
4. IF a test fix requires modifying production code, THEN THE Test_Suite SHALL include a regression test that validates the fix
### Requirement 5: Docker Compose Application Services
**User Story:** As a developer using Docker instead of Kubernetes, I want docker-compose.yml to include all 13 application services and the frontend, so that I can run the full platform locally with a single `docker compose up`.
#### Acceptance Criteria
1. THE Docker_Compose_Stack SHALL define service containers for all 13 application services: scheduler, symbol-registry, ingestion, parser, extractor, aggregation, recommendation, trading-engine, risk-engine, broker-adapter, lake-publisher, query-api, and dashboard
2. THE Docker_Compose_Stack SHALL define a frontend container serving the React dashboard via nginx on port 8080
3. WHEN `docker compose up` is executed, THE Docker_Compose_Stack SHALL start all infrastructure services (PostgreSQL, Redis, MinIO, Ollama, Trino, Hive Metastore, Superset) before application services using dependency ordering
4. WHEN an application service container starts, THE Docker_Compose_Stack SHALL provide health checks that verify the service is ready to accept requests
5. THE Docker_Compose_Stack SHALL configure environment variables for each service matching the defaults documented in `docs/LOCAL_DEV_SETUP.md`, with infrastructure hostnames pointing to Docker Compose service names
6. THE Docker_Compose_Stack SHALL allow users to provide API keys (MARKET_DATA_API_KEY, BROKER_API_KEY, BROKER_API_SECRET) via a `.env` file without modifying docker-compose.yml
7. IF an infrastructure dependency (PostgreSQL, Redis) is not yet healthy, THEN THE Docker_Compose_Stack SHALL delay application service startup using `depends_on` with `condition: service_healthy`
### Requirement 6: Service Feature Documentation
**User Story:** As a user or contributor, I want every service documented with its purpose, configuration, queue interactions, and database tables, so that I can understand how each part of the platform works.
#### Acceptance Criteria
1. THE Documentation_Set SHALL include a dedicated document for each of the 13 services describing its purpose, inputs, outputs, configuration environment variables, and database tables used
2. WHEN a service consumes from or publishes to a Redis queue, THE Documentation_Set SHALL document the queue name, message schema, and processing behavior
3. WHEN a service exposes HTTP endpoints, THE Documentation_Set SHALL reference the API documentation for that service
4. THE Documentation_Set SHALL describe the three signal layers (company, macro, competitive) with their data flow, toggle mechanisms, and weight configurations
5. THE Documentation_Set SHALL document the trading engine features including position sizing, circuit breakers, reserve pool management, risk tier auto-adjustment, backtesting, and notification configuration
### Requirement 7: API Reference Documentation
**User Story:** As a developer integrating with Stonks Oracle, I want a complete API reference for all four FastAPI services, so that I know every endpoint, its parameters, request/response schemas, and error codes.
#### Acceptance Criteria
1. THE Documentation_Set SHALL include an API reference document covering all endpoints of the Query_API, including path, method, query parameters, response schema, and error codes
2. THE Documentation_Set SHALL include an API reference document covering all endpoints of the Symbol_Registry_API, including CRUD operations for companies, aliases, watchlists, sources, exposure profiles, and competitor relationships
3. THE Documentation_Set SHALL include an API reference document covering all endpoints of the Trading_API, including engine control, decision audit, performance metrics, backtesting, notifications, and manual override orders
4. THE Documentation_Set SHALL include an API reference document covering all endpoints of the Risk_API, including order evaluation, approval workflow, and approval expiration
5. WHEN an endpoint accepts query parameters or a request body, THE Documentation_Set SHALL document each parameter with its type, default value, and constraints
6. WHEN an endpoint returns an error, THE Documentation_Set SHALL document the HTTP status code and error response format
### Requirement 8: Helm Chart Configuration Reference
**User Story:** As an operator deploying Stonks Oracle on Kubernetes, I want a complete reference for all Helm chart values, so that I can configure services, resources, secrets, ingress, network policies, and analytics components.
#### Acceptance Criteria
1. THE Documentation_Set SHALL include a Helm configuration reference documenting every key in `values.yaml` with its type, default value, and description
2. THE Documentation_Set SHALL document the `services` block structure including replicas, image, command, tier, port, secrets, resources, and probes for each service
3. THE Documentation_Set SHALL document the `config` block with all ConfigMap environment variables, their defaults, and what they control
4. THE Documentation_Set SHALL document the `secrets` block structure (core, broker, market, gmail, dashboard) and how secrets are injected via `--set` flags during deployment
5. THE Documentation_Set SHALL document the `ingress` block including className, clusterIssuer, and host mappings
6. THE Documentation_Set SHALL document the analytics stack toggles (trino.enabled, hiveMetastore.enabled, superset.enabled) and their resource configurations
7. THE Documentation_Set SHALL document the `pipelineEnabled` toggle and its effect on worker service replicas
8. THE Documentation_Set SHALL document the `networkPolicies.enabled` toggle and the default-deny-ingress behavior
9. THE Documentation_Set SHALL document the value override files (`values-beta.yaml`, `values-paper.yaml`) and their intended deployment stages
### Requirement 9: Docker Deployment Guide
**User Story:** As a developer deploying with Docker Compose, I want a guide explaining all Docker deployment options, environment variables, volume mounts, and operational commands, so that I can run and manage the platform without Kubernetes.
#### Acceptance Criteria
1. THE Documentation_Set SHALL include a Docker deployment guide documenting every service defined in docker-compose.yml with its image, ports, volumes, and environment variables
2. THE Documentation_Set SHALL document the `.env` file format with all required and optional environment variables, their defaults, and descriptions
3. THE Documentation_Set SHALL document volume mounts and data persistence behavior, including how to reset data with `docker compose down -v`
4. THE Documentation_Set SHALL document health check configurations and how to verify all services are running
5. THE Documentation_Set SHALL document the Dockerfile build arguments (SERVICE_CMD) and how to build custom service images
6. THE Documentation_Set SHALL document operational commands for starting, stopping, restarting individual services, viewing logs, and scaling replicas
### Requirement 10: Kubernetes Architecture Diagram
**User Story:** As an operator deploying on Kubernetes, I want a Mermaid diagram showing how Stonks Oracle runs in a K8s cluster, so that I can understand the deployment topology, networking, and infrastructure dependencies.
#### Acceptance Criteria
1. THE Documentation_Set SHALL include a Mermaid diagram showing all 13 application services deployed as Kubernetes Deployments within the `stonks-oracle` namespace
2. THE diagram SHALL show external cluster services (PostgreSQL, Redis, MinIO, Ollama) in their respective namespaces with cross-namespace service references
3. THE diagram SHALL show Traefik ingress routes mapping external domains to internal services (stonks.celestium.life → dashboard, stonks-api.celestium.life → query-api, etc.)
4. THE diagram SHALL show network policy boundaries indicating which services can communicate with each other
5. THE diagram SHALL show the analytics plane (Trino, Hive Metastore, Superset) deployed within the stonks-oracle namespace and their connections to MinIO
6. THE diagram SHALL show Helm-managed secrets (core, broker, market, gmail) and which services consume them
7. THE diagram SHALL distinguish between API-tier services (with ingress), pipeline-tier workers (queue-driven), and trading-tier services
### Requirement 11: Docker Compose Architecture Diagram
**User Story:** As a developer running the platform locally with Docker Compose, I want a Mermaid diagram showing how all containers are wired together, so that I can understand port mappings, volume mounts, and service dependencies.
#### Acceptance Criteria
1. THE Documentation_Set SHALL include a Mermaid diagram showing all infrastructure containers (PostgreSQL, Redis, MinIO, Ollama, Trino, Hive Metastore, Superset) and all 13 application service containers as defined in docker-compose.yml
2. THE diagram SHALL show host port mappings for externally accessible services (PostgreSQL:5432, Redis:6379, MinIO:9000/9001, Ollama:11434, Trino:8080, Superset:8088, Dashboard:8080, Query API:8000)
3. THE diagram SHALL show Docker Compose `depends_on` relationships and health check dependencies between infrastructure and application services
4. THE diagram SHALL show named volumes (pgdata, miniodata, ollama_models, hive_data, superset_data) and which containers mount them
5. THE diagram SHALL show the `.env` file providing API keys (MARKET_DATA_API_KEY, BROKER_API_KEY, BROKER_API_SECRET) to relevant service containers
6. THE diagram SHALL show internal Docker network connectivity between containers using Docker Compose service names as hostnames
### Requirement 12: Data Pipeline Architecture Diagram
**User Story:** As a user or contributor, I want a Mermaid diagram showing the end-to-end data pipeline from external data sources through signal processing to trade execution, so that I can understand how data flows through the system.
#### Acceptance Criteria
1. THE Documentation_Set SHALL include a Mermaid diagram showing the complete data pipeline from external sources (Polygon.io, news APIs, SEC filings, macro news sources) through ingestion, parsing, extraction, aggregation, recommendation, risk evaluation, and trade execution
2. THE diagram SHALL show the Redis queue topology connecting pipeline stages (ingestion → parsing → extraction → aggregation → recommendation → broker) with queue names
3. THE diagram SHALL show the three signal layers (company, macro, competitive) as distinct processing paths that merge in the aggregation stage
4. THE diagram SHALL show data stores at each stage: MinIO for raw artifacts, PostgreSQL for structured data, Redis for queues and caching
5. THE diagram SHALL show the trading engine decision loop: recommendation polling → position sizing → risk evaluation → order execution → broker submission → fill tracking
6. THE diagram SHALL show the analytical branch: lake publisher writing Parquet fact tables to MinIO, queryable via Trino, visualized in Superset and the React dashboard
7. THE diagram SHALL show external integrations at their connection points: Ollama for LLM extraction, Alpaca for trade execution, AWS SNS and Gmail for notifications
### Requirement 13: AI Agent Building Guide
**User Story:** As a user or contributor, I want a guide explaining how each of the three AI agents works — document extractor, event classifier, and thesis rewriter — including how to configure them, create variants, tune prompts, and monitor performance, so that I can customize and extend the AI capabilities of the platform.
#### Acceptance Criteria
1. THE Documentation_Set SHALL include an AI agent guide documenting the three built-in agents: `document-extractor` (structured intelligence extraction from news/filings), `event-classifier` (macro/geopolitical event classification), and `thesis-rewriter` (LLM-enhanced recommendation thesis generation)
2. FOR each agent, THE Documentation_Set SHALL document its purpose, input data, output schema, default model, system prompt structure, and user prompt template
3. THE Documentation_Set SHALL document the `ai_agents` database table schema and how agents are registered (system-seeded vs user-created via the API)
4. THE Documentation_Set SHALL document the `agent_variants` table and how to create, activate, and deactivate variants for A/B testing different models or prompts
5. THE Documentation_Set SHALL document the `AgentConfigResolver` module including the TTL cache (60-second default), COALESCE-based variant override logic, and fallback behavior when no DB config exists
6. THE Documentation_Set SHALL document the agent performance logging system and how to query `agent_performance_log` to compare variant effectiveness
7. THE Documentation_Set SHALL document the API endpoints for managing agents (CRUD on `/api/agents`) and testing agent configurations (`/api/agents/{id}/test`)
8. THE Documentation_Set SHALL include a step-by-step guide for creating a new agent variant with a different model or prompt and activating it for live traffic
### Requirement 14: Backup and Restore Guide
**User Story:** As an operator, I want a guide documenting all backup and restore scripts, their options, storage locations, and retention policies, so that I can protect data and recover from failures.
#### Acceptance Criteria
1. THE Documentation_Set SHALL include a backup and restore guide documenting every script in `scripts/` related to backup and restore: `backup-db.sh`, `restore-db.sh`, `backup-redis.sh`, `backup.sh`, and `restore.sh`
2. FOR each backup script, THE Documentation_Set SHALL document its CLI arguments, what data it captures, where backups are stored, and retention/pruning behavior (e.g., keeps last 7)
3. FOR each restore script, THE Documentation_Set SHALL document its CLI arguments, what it restores, the service scale-down/scale-up procedure it performs, and any data loss implications
4. THE Documentation_Set SHALL document the MinIO upload option (`--upload-minio`) for off-host backup storage
5. THE Documentation_Set SHALL document the full database nuke and rebuild procedure including connection termination, database drop, Redis flush, redeploy, and re-seed steps
6. THE Documentation_Set SHALL document recommended backup schedules and how to automate backups via cron or Kubernetes CronJobs
### Requirement 15: Observability and Prometheus Metrics Reference
**User Story:** As an operator, I want a reference documenting all Prometheus metrics exposed by the platform, the alerting rules, and how to monitor pipeline health, so that I can set up dashboards and respond to incidents.
#### Acceptance Criteria
1. THE Documentation_Set SHALL include an observability reference documenting the `/metrics` endpoint on the query API and how to configure Prometheus to scrape it
2. THE Documentation_Set SHALL document all Prometheus counters, gauges, and histograms emitted by each service, including metric name, labels, and what they measure (e.g., `EXTRACTION_ATTEMPTS`, `EXTRACTION_DURATION`, `AGGREGATION_WINDOWS_COMPUTED`, `AGGREGATION_SIGNALS_PROCESSED`, `RECOMMENDATION_GENERATED`, `RECOMMENDATION_CONFIDENCE`, alerting counters)
3. THE Documentation_Set SHALL document the alerting module (`services/shared/alerting.py`) including all alert rules, their thresholds, evaluation windows, and the ConfigMap environment variables that control them (`ALERT_SOURCE_FAILURE_THRESHOLD`, `ALERT_SCHEMA_FAILURE_RATE_THRESHOLD`, `ALERT_LAKE_LAG_THRESHOLD_MINUTES`, `ALERT_BROKER_ERROR_THRESHOLD`, etc.)
4. THE Documentation_Set SHALL document the structured JSON logging format, trace context propagation (trace_id, span_id), and how to query logs for debugging pipeline issues
5. THE Documentation_Set SHALL document the dead-letter queue system including queue names, how failed jobs are routed there, and how to replay them using the dead-letter tooling
6. THE Documentation_Set SHALL document recommended Prometheus/Grafana dashboard configurations or queries for monitoring ingestion throughput, extraction latency, aggregation volume, recommendation generation rate, and trading engine activity
### Requirement 16: README Resource Links
**User Story:** As a user landing on the repository, I want the README to link to all documentation resources, so that I can navigate to any guide, reference, or diagram from a single entry point.
#### Acceptance Criteria
1. WHEN the README is updated, THE README SHALL include a documentation section with links to every document in the Documentation_Set
2. THE README SHALL link to the API reference documents for all four FastAPI services
3. THE README SHALL link to the Helm chart configuration reference
4. THE README SHALL link to the Docker deployment guide
5. THE README SHALL link to all three architecture diagram documents (Kubernetes, Docker Compose, and Data Pipeline)
6. THE README SHALL link to the per-service feature documentation
7. THE README SHALL link to the AI agent building guide
8. THE README SHALL link to the backup and restore guide
9. THE README SHALL link to the observability and Prometheus metrics reference
10. THE README SHALL replace the existing ASCII architecture diagram with the Mermaid architecture diagram or link to it
11. THE README SHALL preserve all existing content (license, features, tech stack, project structure, deployment instructions) while adding the new documentation links
@@ -0,0 +1,223 @@
# Implementation Plan: Comprehensive Quality & Documentation
## Overview
This plan implements three pillars for the Stonks Oracle platform: (1) unit test coverage for the scheduler and ingestion services plus fixing pre-existing test failures, (2) extending docker-compose.yml with all 13 application services and the frontend, and (3) producing comprehensive documentation covering services, APIs, Helm configuration, Docker deployment, architecture diagrams, AI agents, backup/restore, observability, and README resource links. Tasks are ordered so tests come first (catch regressions early), then Docker Compose (infrastructure), then documentation (references verified code).
## Tasks
- [x] 1. Write scheduler service unit tests
- [x] 1.1 Create `tests/test_scheduler_unit.py` with unit tests for scheduler pure functions and orchestration
- Import scheduler functions from `services/scheduler/app.py`
- Mock `asyncpg.Pool` (`.fetch()`, `.fetchrow()`, `.fetchval()`, `.execute()`) and `redis.asyncio.Redis` (`.rpush()`, `.set()`, `.get()`, `.incr()`, `.expire()`, `.decr()`, `.delete()`)
- Write 8+ test cases covering: `get_cadence_for_source`, `compute_backoff`, `is_source_due`, `build_job_payload`, `schedule_cycle` (mocked DB/Redis), `check_rate_limit`, `recover_stale_documents`, `retry_failed_extractions`
- Verify error handling: DB/Redis connection failures handled without crashing
- Use `pytest-asyncio` for async test functions, `unittest.mock.AsyncMock` and `unittest.mock.patch`
- _Requirements: 1.1, 1.2, 1.3, 1.4_
- [x] 1.2 Write additional edge-case unit tests for scheduler
- Test boundary conditions: zero polling interval, max retry count, empty source list
- Test rate limiting edge cases: global Polygon limit, per-type limits
- _Requirements: 1.3, 1.4_
- [x] 2. Write ingestion service unit tests
- [x] 2.1 Create `tests/test_ingestion_unit.py` with unit tests for ingestion worker
- Import ingestion functions from `services/ingestion/worker.py`
- Mock adapters as `AsyncMock` returning `AdapterResult` with controlled `error`, `items`, `content_hash`, `raw_payload`
- Mock `asyncpg.Pool` for `ingestion_runs` INSERT/UPDATE, `persist_ingestion_items`, `record_retrieval_failure`
- Mock `redis.asyncio.Redis` for dedupe checks, queue pushes, DLQ routing
- Mock `minio.Minio` for `upload_raw_artifact`
- Write 6+ test cases covering: successful job processing, adapter error with retry, retry exhaustion → dead-letter queue, content hash deduplication skip, cross-source dedup via `dedupe_items`, error handling paths
- _Requirements: 2.1, 2.2, 2.3, 2.4_
- [x] 2.2 Write additional edge-case unit tests for ingestion
- Test empty adapter response, partial failures, multiple items in single job
- _Requirements: 2.1, 2.4_
- [x] 3. Checkpoint — Verify new unit tests pass
- Run `pytest tests/test_scheduler_unit.py tests/test_ingestion_unit.py -x --tb=short -q`
- Ensure all tests pass, ask the user if questions arise.
- [x] 4. Fix pre-existing test failures
- [x] 4.1 Fix `tests/test_extractor_prompts.py`
- Run the file individually to diagnose failures
- Fix test setup (mock configuration, fixture data) or production code as needed
- Preserve original test intent and assertions
- If production code changes are needed, add regression tests
- _Requirements: 3.1, 3.5_
- [x] 4.2 Fix `tests/test_extractor_schemas.py`
- Run the file individually to diagnose failures
- Fix test setup or production code as needed
- Preserve original test intent and assertions
- _Requirements: 3.2, 3.5_
- [x] 4.3 Fix `tests/test_ollama_client.py`
- Run the file individually to diagnose failures
- Fix test setup or production code as needed
- Preserve original test intent and assertions
- _Requirements: 3.3, 3.5_
- [x] 4.4 Fix `tests/test_filings_adapter.py`
- Run the file individually to diagnose failures
- Fix test setup or production code as needed
- Preserve original test intent and assertions
- _Requirements: 3.4, 3.5_
- [x] 5. Checkpoint — Full test suite green
- Run `pytest tests/ -x --tb=short -q` and verify zero failures
- Run `ruff check services/` and verify zero violations
- Verify all `test_pbt_*` files pass unchanged
- If any production code was modified, confirm regression tests exist
- Ensure all tests pass, ask the user if questions arise.
- _Requirements: 4.1, 4.2, 4.3, 4.4_
- [x] 6. Add application services to docker-compose.yml
- [x] 6.1 Add shared environment anchor and all 14 service definitions to `docker-compose.yml`
- Define `x-app-env` YAML anchor with common environment variables (POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD, REDIS_HOST, REDIS_PORT, MINIO_ENDPOINT, MINIO_ACCESS_KEY, MINIO_SECRET_KEY, OLLAMA_BASE_URL)
- Add 13 application service definitions: scheduler (using `docker/Dockerfile.scheduler`), symbol-registry, ingestion, parser, extractor, aggregation, recommendation, trading-engine, risk-engine, broker-adapter, lake-publisher, query-api — each using `docker/Dockerfile` with appropriate `SERVICE_CMD` build arg
- Add dashboard service using `frontend/Dockerfile` on port 3000:8080
- Configure `depends_on` with `condition: service_healthy` for infrastructure dependencies
- Add health checks: FastAPI services use `curl -f http://localhost:8000/health`, workers use process liveness
- Configure `env_file: .env` on services needing API keys (ingestion, broker-adapter, trading-engine)
- Map host ports: symbol-registry:8001, trading-engine:8002, risk-engine:8003, query-api:8004, dashboard:3000
- _Requirements: 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7_
- [x] 6.2 Validate docker-compose.yml configuration
- Run `docker compose config` to verify the updated file parses correctly
- _Requirements: 5.1_
- [x] 7. Checkpoint — Tests and Docker Compose validated
- Run `pytest tests/ -x --tb=short -q` to confirm no regressions
- Run `docker compose config` to confirm valid YAML
- Ensure all tests pass, ask the user if questions arise.
- [x] 8. Write per-service feature documentation
- [x] 8.1 Create `docs/services.md` documenting all 13 services
- For each service: purpose, entry point module path, configuration environment variables, database tables read/written, Redis queues consumed/published with message schemas
- Include queue topology table (queue name → producer → consumer)
- Document the three signal layers (company, macro, competitive) with data flow, toggles, and weight configurations
- Document trading engine features: position sizing, circuit breakers, reserve pool, risk tier auto-adjustment, backtesting, notifications
- Cross-reference API documentation for services with HTTP endpoints
- _Requirements: 6.1, 6.2, 6.3, 6.4, 6.5_
- [x] 9. Write API reference documentation
- [x] 9.1 Create `docs/api-reference.md` covering all four FastAPI services
- Document all Query API endpoints (~40+): path, method, query parameters (type, default, constraints), request body schema, response schema, error codes
- Document all Symbol Registry API endpoints: companies CRUD, aliases, watchlists, sources, exposure profiles, competitor relationships, competitor inference
- Document all Trading API endpoints: health/readiness, engine status, config update, pause/resume, reset, decisions audit, performance metrics/history, backtesting, notifications config/history, override orders, debug state
- Document all Risk API endpoints: order evaluation (POST /evaluate), health, pending approvals, approval review, approval expiration
- Inspect actual route definitions in `services/api/app.py`, `services/symbol_registry/app.py`, `services/trading/app.py`, `services/risk/app.py`
- _Requirements: 7.1, 7.2, 7.3, 7.4, 7.5, 7.6_
- [x] 10. Write Helm chart configuration reference
- [x] 10.1 Create `docs/helm-reference.md` documenting all Helm values
- Document `image` block: registry, pullPolicy, tag
- Document `pipelineEnabled` toggle and effect on worker replicas
- Document `services` block: per-service structure (replicas, image, command, tier, port, secrets, resources, probes)
- Document `config` block: all ConfigMap environment variables with defaults and descriptions
- Document `secrets` block: core, broker, market, gmail, dashboard — injection via `--set` flags
- Document `ingress` block: className, clusterIssuer, host mappings
- Document analytics stack toggles: trino.enabled, hiveMetastore.enabled, superset.enabled with resources
- Document `networkPolicies.enabled` and default-deny-ingress behavior
- Document value override files: `values-beta.yaml`, `values-paper.yaml` and deployment stages
- _Requirements: 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9_
- [x] 11. Write Docker deployment guide
- [x] 11.1 Create `docs/docker-deployment.md` with complete Docker deployment guide
- Document every service with image, ports, volumes, environment variables
- Document `.env` file format with all required/optional variables, defaults, descriptions
- Document volume mounts and data persistence (pgdata, miniodata, ollama_models, hive_data, superset_data), reset with `docker compose down -v`
- Document health check configurations and verification commands
- Document Dockerfile build arguments (`SERVICE_CMD`) and custom image builds
- Document operational commands: start, stop, restart, logs, scale, reset
- _Requirements: 9.1, 9.2, 9.3, 9.4, 9.5, 9.6_
- [x] 12. Checkpoint — Documentation progress check
- Verify `docs/services.md`, `docs/api-reference.md`, `docs/helm-reference.md`, `docs/docker-deployment.md` exist and render valid Markdown
- Ensure all tests pass, ask the user if questions arise.
- [x] 13. Write architecture diagrams
- [x] 13.1 Create `docs/architecture-kubernetes.md` with Kubernetes deployment Mermaid diagram
- Show all 13 services in `stonks-oracle` namespace grouped by tier (api, processing, trading, orchestration, analytics, frontend)
- Show external cluster services (PostgreSQL, Redis, MinIO, Ollama) in their namespaces
- Show Traefik ingress routes to external domains
- Show network policy boundaries
- Show analytics plane (Trino, Hive Metastore, Superset) and MinIO connections
- Show Helm-managed secrets (core, broker, market, gmail) with consumer mapping
- Distinguish API-tier (with ingress), pipeline-tier (queue-driven), and trading-tier services
- _Requirements: 10.1, 10.2, 10.3, 10.4, 10.5, 10.6, 10.7_
- [x] 13.2 Create `docs/architecture-docker-compose.md` with Docker Compose Mermaid diagram
- Show all infrastructure + application containers
- Show host port mappings for externally accessible services
- Show `depends_on` relationships and health check dependencies
- Show named volumes and mount points
- Show `.env` file providing API keys to relevant containers
- Show internal Docker network connectivity
- _Requirements: 11.1, 11.2, 11.3, 11.4, 11.5, 11.6_
- [x] 13.3 Create `docs/architecture-data-pipeline.md` with data pipeline Mermaid diagram
- Show complete pipeline: external sources → ingestion → parsing → extraction → aggregation → recommendation → risk → trading → broker
- Show Redis queue topology with queue names
- Show three signal layers as distinct paths merging at aggregation
- Show data stores at each stage (MinIO, PostgreSQL, Redis)
- Show trading engine decision loop
- Show analytical branch: lake publisher → MinIO/Parquet → Trino → Superset/Dashboard
- Show external integrations: Ollama, Alpaca, AWS SNS, Gmail
- _Requirements: 12.1, 12.2, 12.3, 12.4, 12.5, 12.6, 12.7_
- [x] 14. Write AI agent building guide
- [x] 14.1 Create `docs/ai-agents.md` with AI agent guide
- Document three built-in agents: document-extractor, event-classifier, thesis-rewriter — purpose, input data, output schema, default model, system prompt structure, user prompt template
- Document `ai_agents` table schema and registration (system-seeded vs API-created)
- Document `agent_variants` table: create, activate, deactivate variants for A/B testing
- Document `AgentConfigResolver` module: TTL cache (60s), COALESCE-based variant override, fallback behavior
- Document performance logging: `agent_performance_log` table, querying for variant comparison
- Document API endpoints: CRUD on `/api/agents`, test endpoint `/api/agents/{id}/test`
- Include step-by-step guide: creating a new variant with different model/prompt and activating it
- _Requirements: 13.1, 13.2, 13.3, 13.4, 13.5, 13.6, 13.7, 13.8_
- [x] 15. Write backup and restore guide
- [x] 15.1 Create `docs/backup-restore.md` with backup and restore guide
- Document all scripts in `scripts/`: `backup-db.sh`, `restore-db.sh`, `backup-redis.sh`, `backup.sh`, `restore.sh`
- For each backup script: CLI arguments, data captured, storage location, retention/pruning (keeps last 7)
- For each restore script: CLI arguments, what it restores, service scale-down/up procedure, data loss implications
- Document MinIO upload option (`--upload-minio`) for off-host storage
- Document full nuke-and-rebuild procedure: connection termination, DB drop, Redis flush, redeploy, re-seed
- Document recommended backup schedules and automation (cron, Kubernetes CronJobs)
- _Requirements: 14.1, 14.2, 14.3, 14.4, 14.5, 14.6_
- [x] 16. Write observability and metrics reference
- [x] 16.1 Create `docs/observability.md` with observability reference
- Document `/metrics` endpoint on query-api and Prometheus scrape configuration
- Document all Prometheus counters, gauges, histograms from `services/shared/metrics.py` — ingestion, parsing, extraction, aggregation, recommendation, lake, trading, alerting, DLQ, active jobs metrics with names, labels, descriptions
- Document alerting module (`services/shared/alerting.py`): 4 alert rules, thresholds, evaluation windows, ConfigMap variables
- Document structured JSON logging format, trace context (trace_id, span_id), log querying
- Document dead-letter queue system: queue names (`stonks:dlq:<queue>`), routing, replay tooling
- Document recommended Prometheus/Grafana queries for monitoring
- _Requirements: 15.1, 15.2, 15.3, 15.4, 15.5, 15.6_
- [x] 17. Update README with documentation links
- [x] 17.1 Update `README.md` with documentation section and resource links
- Add "Documentation" section with links to all docs: services.md, api-reference.md, helm-reference.md, docker-deployment.md, architecture-kubernetes.md, architecture-docker-compose.md, architecture-data-pipeline.md, ai-agents.md, backup-restore.md, observability.md
- Replace ASCII architecture diagram with Mermaid diagram or link to architecture diagram docs
- Preserve all existing content: license, features, tech stack, project structure, deployment instructions
- _Requirements: 16.1, 16.2, 16.3, 16.4, 16.5, 16.6, 16.7, 16.8, 16.9, 16.10, 16.11_
- [x] 18. Final checkpoint — Full verification
- Run `pytest tests/ -x --tb=short -q` — zero failures
- Run `ruff check services/` — zero violations
- Run `docker compose config` — validates successfully
- Verify all `test_pbt_*` files pass unchanged
- Verify all documentation files exist in `docs/` and render valid Markdown
- Ensure all tests pass, ask the user if questions arise.
## Notes
- Tasks marked with `*` are optional and can be skipped for faster MVP
- Each task references specific requirements for traceability
- Checkpoints ensure incremental validation
- No property-based tests are included — the design assessment confirmed PBT is not applicable to this feature
- Existing `test_pbt_*` files (22 files) must remain passing throughout
- The implementation language is Python (with Markdown for documentation), matching the existing codebase
@@ -0,0 +1 @@
{"specId": "d2fe9091-6423-482c-a4ce-3cd72e62eb23", "workflowType": "requirements-first", "specType": "feature"}
@@ -0,0 +1,153 @@
# Design Document: Intelligence Pipeline Deep Dive
## Overview
This design specifies the structure, content, and creation process for a 6-page narrative deep-dive document covering the full intelligence-to-decision pipeline in Stonks Oracle. The deliverable consists of Markdown narrative pages, an index file, and standalone Mermaid diagram files — all stored under `docs/intelligence-pipeline-deep-dive/`.
The document targets technical readers who want to understand how raw data enters the system, gets processed by AI agents, produces structured signals, accumulates into trend summaries, and ultimately drives autonomous trading decisions. Unlike the existing reference docs (`docs/services.md`, `docs/architecture-data-pipeline.md`), this deliverable is narrative and explanatory — it tells the story of data flowing through the platform end-to-end.
**Key design decision**: This is a documentation-only deliverable. No application code, database schemas, or infrastructure changes are involved. The output is purely Markdown files and Mermaid diagram files.
### Existing Documentation Landscape
The codebase already has several reference documents that this deep-dive complements:
| Document | Purpose | Style |
|----------|---------|-------|
| `docs/architecture-data-pipeline.md` | Queue topology, data store summary, Mermaid flow diagrams | Reference diagrams + tables |
| `docs/llm-to-trade-pipeline.md` | End-to-end data flow from model output to trade | Narrative + tables + code blocks |
| `docs/services.md` | Per-service configuration, tables, queues, behaviors | Reference manual |
| `docs/ai-agents.md` | AI agent configuration, variants, A/B testing, API | Guide + reference |
The deep-dive document will reference these existing docs for readers who want deeper detail, while providing a cohesive narrative that connects all pipeline stages into a single story.
## Architecture
### File Organization
```
docs/intelligence-pipeline-deep-dive/
├── index.md
├── 01-data-ingestion-and-preparation.md
├── 02-ai-agent-processing-and-extraction.md
├── 03-signal-scoring-and-weighted-signals.md
├── 04-trend-aggregation-and-accumulating-signals.md
├── 05-recommendation-generation.md
├── 06-trading-decisions-and-execution.md
└── diagrams/
├── ingestion-to-extraction-flow.md
├── three-layer-signal-merging.md
├── recommendation-generation-flow.md
├── trading-engine-decision-loop.md
├── weighted-signal-computation.md
└── trend-accumulation-escalation.md
```
### Content Flow
Each page covers one pipeline stage and ends with a transitional paragraph previewing the next page. Cross-references between pages use relative Markdown links. Diagrams are stored as standalone Mermaid files in the `diagrams/` subdirectory and linked from the narrative pages (not embedded inline).
```mermaid
flowchart LR
P1["Page 1\nData Ingestion"] --> P2["Page 2\nAI Extraction"]
P2 --> P3["Page 3\nSignal Scoring"]
P3 --> P4["Page 4\nTrend Aggregation"]
P4 --> P5["Page 5\nRecommendations"]
P5 --> P6["Page 6\nTrading Execution"]
```
## Components and Interfaces
### Index File (`index.md`)
The index provides:
- A brief introduction to the deep-dive document series
- A numbered table of contents linking to all 6 pages
- A diagrams section linking to all Mermaid diagram files
- References to existing documentation for additional context
### Narrative Pages (01 through 06)
Each page follows a consistent structure:
1. **Title and introduction** — what this stage does and why it matters
2. **Narrative body** — explanatory prose describing the pipeline stage, referencing actual code modules (`services/extractor/main.py`), database tables (`document_impact_records`), Redis queues (`stonks:queue:extraction`), and Pydantic schemas (`ExtractionResult`)
3. **Diagram references** — links to relevant Mermaid diagram files in `diagrams/`
4. **Transition** — a closing paragraph that previews the next page
### Mermaid Diagram Files
Each diagram file contains:
1. A brief title comment
2. A single Mermaid code block
3. Service labels include both human-readable names and Python module paths
4. Queue labels use full Redis key patterns
5. Database references use exact PostgreSQL table names
Minimum 6 diagrams covering:
- **Ingestion-to-extraction flow**: Scheduler → Ingestion → Parser → Extractor, with queues and storage
- **Three-layer signal merging**: Company, Macro, and Competitive layers converging into aggregation
- **Recommendation generation flow**: Suppression → Eligibility → Thesis → Risk classification
- **Trading engine decision loop**: Pre-trade checks → Position sizing → Order submission
- **Weighted signal computation**: Component breakdown of the composite weight formula
- **Trend accumulation and escalation**: How consecutive signals strengthen trends and escalate actions
### Page Content Mapping
| Page | Primary Code Modules | Key Database Tables | Key Queues |
|------|---------------------|---------------------|------------|
| 01 - Ingestion | `services/scheduler/app.py`, `services/ingestion/worker.py`, `services/parser/worker.py` | `documents`, `ingestion_runs`, `document_company_mentions` | `stonks:queue:ingestion`, `stonks:queue:parsing` |
| 02 - AI Extraction | `services/extractor/main.py`, `services/extractor/client.py`, `services/extractor/prompts.py`, `services/extractor/schemas.py`, `services/extractor/event_classifier.py`, `services/shared/agent_config.py` | `document_intelligence`, `document_impact_records`, `global_events`, `macro_impact_records`, `ai_agents`, `agent_variants` | `stonks:queue:extraction`, `stonks:queue:macro_classification`, `stonks:queue:aggregation` |
| 03 - Signal Scoring | `services/aggregation/scoring.py` | `document_impact_records`, `macro_impact_records`, `competitive_signal_records`, `risk_configs` | — |
| 04 - Trend Aggregation | `services/aggregation/worker.py`, `services/aggregation/contradiction.py`, `services/aggregation/projection.py`, `services/aggregation/pattern_matcher.py`, `services/aggregation/signal_propagation.py` | `trend_windows`, `trend_history`, `trend_evidence`, `trend_projections` | `stonks:queue:aggregation`, `stonks:queue:recommendation` |
| 05 - Recommendations | `services/recommendation/main.py`, `services/recommendation/suppression.py`, `services/recommendation/eligibility.py`, `services/recommendation/thesis_llm.py` | `recommendations`, `recommendation_evidence`, `risk_evaluations` | `stonks:queue:recommendation` |
| 06 - Trading | `services/trading/engine.py`, `services/trading/position_sizer.py`, `services/trading/circuit_breaker.py`, `services/trading/reserve_pool.py`, `services/trading/risk_tier_controller.py`, `services/trading/stop_loss_manager.py` | `trading_decisions`, `orders`, `positions`, `portfolio_snapshots`, `reserve_pool_ledger`, `risk_tier_history`, `circuit_breaker_events` | `stonks:queue:broker_orders` |
## Data Models
This feature produces only documentation files. There are no new data models, database tables, or schema changes.
The narrative pages will reference existing data models from the codebase:
- **`WeightedSignal`** (`services/aggregation/scoring.py`) — document reference + composite weight + sentiment + impact
- **`SignalWeight`** (`services/aggregation/scoring.py`) — breakdown of recency, credibility, novelty, confidence gate, market context multiplier
- **`ScoringConfig`** (`services/aggregation/scoring.py`) — tunable parameters for signal scoring
- **`ExtractionResult`** / **`CompanyImpact`** (`services/extractor/schemas.py`) — structured JSON output from document extraction
- **`GlobalEventSchema`** (`services/extractor/event_classifier.py`) — macro event classification output
- **`TrendSummary`** (`services/shared/schemas.py`) — rolling trend for a ticker across a time window
- **`Recommendation`** (`services/shared/schemas.py`) — actionable trade recommendation
- **`TradingDecision`** (`services/trading/engine.py`) — audit record of every trading evaluation
## Error Handling
Since this is a documentation-only deliverable, there is no runtime error handling to design. The primary quality concern is **accuracy** — ensuring that all code module paths, database table names, Redis queue keys, schema field names, and configuration values referenced in the narrative match the actual codebase.
### Accuracy Verification Strategy
1. **Code module paths**: Every module path referenced in the narrative (e.g., `services/aggregation/scoring.py`) must correspond to an existing file in the repository.
2. **Database table names**: Table names must match those defined in `infra/migrations/` SQL files.
3. **Redis queue keys**: Queue names must match constants in `services/shared/redis_keys.py`.
4. **Schema class names**: Pydantic model names must match their definitions in `services/shared/schemas.py` and service-specific schema files.
5. **Configuration values**: Environment variable names and default values must match `services/shared/config.py` and service-specific configuration.
### Cross-Reference Integrity
All inter-page links (e.g., `[Page 3](03-signal-scoring-and-weighted-signals.md)`) and diagram links (e.g., `[diagram](diagrams/ingestion-to-extraction-flow.md)`) must resolve to files that exist in the deliverable.
## Testing Strategy
**Property-based testing does not apply to this feature.** The deliverable is purely documentation — Markdown narrative pages and Mermaid diagram files. There are no functions, data transformations, or code logic to test.
### Why PBT Does Not Apply
- The output is static Markdown text, not executable code
- There are no input/output functions to verify properties against
- There is no data transformation logic that varies with input
- The quality criteria (narrative coherence, codebase accuracy, cross-reference integrity) are best verified through manual review
### Verification Approach
1. **File existence check**: Verify all 6 page files, the index file, and all diagram files exist at the expected paths
2. **Link integrity**: Verify all inter-page and diagram links resolve to existing files
3. **Mermaid syntax**: Verify each diagram file contains valid Mermaid syntax by checking for proper `flowchart` or `graph` declarations
4. **Codebase reference spot-checks**: Verify a sample of referenced module paths, table names, and queue keys against the actual codebase
5. **Narrative flow**: Manual review to confirm each page ends with a transition to the next and the overall story is coherent
@@ -0,0 +1,155 @@
# Requirements Document
## Introduction
This specification defines a 6-page narrative deep-dive document (plus separate Mermaid diagram files) that explains the full intelligence-to-decision pipeline in Stonks Oracle. The document targets a technical reader who wants to understand how raw data enters the system, gets processed by AI agents, produces structured signals, accumulates into trend summaries, and ultimately drives autonomous trading decisions. Unlike the existing service reference and API docs, this deliverable is narrative and explanatory — it tells the story of data flowing through the platform end-to-end, referencing actual code modules, database tables, queue names, and schemas from the codebase.
## Glossary
- **Deep_Dive_Document**: The 6-page Markdown document delivered under `docs/intelligence-pipeline-deep-dive/`, consisting of pages 01 through 06 covering the full intelligence-to-decision pipeline.
- **Mermaid_Diagram_File**: A standalone Markdown file containing a single Mermaid diagram block, stored alongside the narrative pages in `docs/intelligence-pipeline-deep-dive/diagrams/`.
- **Pipeline**: The end-to-end data flow from external source ingestion through AI extraction, signal aggregation, recommendation generation, and autonomous trading execution.
- **Signal_Layer**: One of three independent signal sources (Company, Macro, Competitive) that produce `WeightedSignal` objects merged by the Aggregation_Engine.
- **Aggregation_Engine**: The `services/aggregation/` module that merges weighted signals from all three layers into `TrendSummary` objects across five time windows.
- **Trading_Engine**: The `services/trading/engine.py` module that polls recommendations and executes autonomous paper trades through a multi-check decision loop.
- **Extractor**: The `services/extractor/` module that uses Ollama LLM inference to produce structured JSON intelligence from documents.
- **WeightedSignal**: The `services.aggregation.scoring.WeightedSignal` dataclass that pairs a document reference with a composite aggregation weight.
- **TrendSummary**: The `services.shared.schemas.TrendSummary` Pydantic model representing a rolling trend for a ticker across a specific time window.
- **Recommendation**: The `services.shared.schemas.Recommendation` Pydantic model representing an actionable trade recommendation with action, mode, confidence, thesis, and position sizing.
- **Circuit_Breaker**: The `services/trading/circuit_breaker.py` safety mechanism that halts trading when risk thresholds (daily loss, single-position loss, volatility clustering) are breached.
## Requirements
### Requirement 1: Document Structure and File Organization
**User Story:** As a technical reader, I want the deep-dive organized into clearly separated pages with a consistent structure, so that I can navigate to specific pipeline stages without reading the entire document.
#### Acceptance Criteria
1. THE Deep_Dive_Document SHALL consist of exactly 6 Markdown page files named `01-data-ingestion-and-preparation.md` through `06-trading-decisions-and-execution.md`, stored under `docs/intelligence-pipeline-deep-dive/`.
2. THE Deep_Dive_Document SHALL include an `index.md` file that provides a table of contents linking to all 6 pages and all Mermaid_Diagram_Files.
3. WHEN a page references a Mermaid diagram, THE Deep_Dive_Document SHALL link to the corresponding Mermaid_Diagram_File stored in `docs/intelligence-pipeline-deep-dive/diagrams/` rather than embedding the diagram inline.
4. THE Deep_Dive_Document SHALL include a minimum of 4 separate Mermaid_Diagram_Files covering: (a) the ingestion-to-extraction flow, (b) the three signal layers merging into aggregation, (c) the recommendation generation pipeline, and (d) the trading engine decision loop.
5. WHEN a page references a code module, THE Deep_Dive_Document SHALL use the full Python module path (e.g., `services/extractor/prompts.py`) rather than abbreviated names.
6. WHEN a page references a database table, THE Deep_Dive_Document SHALL use the exact table name as defined in the PostgreSQL schema (e.g., `document_impact_records`, `trend_windows`).
7. WHEN a page references a Redis queue, THE Deep_Dive_Document SHALL use the full key pattern as defined in `services/shared/redis_keys.py` (e.g., `stonks:queue:extraction`).
### Requirement 2: Page 1 — Data Ingestion and Preparation
**User Story:** As a technical reader, I want to understand how raw data enters Stonks Oracle and gets prepared for AI processing, so that I can trace the origin of any signal back to its external source.
#### Acceptance Criteria
1. THE Deep_Dive_Document page 01 SHALL explain the four categories of input data: news articles (Polygon.io), SEC filings (EDGAR), market data (Polygon.io grouped daily and intraday bars), and macro/geopolitical events (macro news APIs).
2. THE Deep_Dive_Document page 01 SHALL describe the Scheduler's role in orchestrating ingestion cycles, including cadence polling intervals per source type (`market_api`: 300s, `news_api`: 300s, `filings_api`: 3600s, `macro_news`: 600s), rate limiting, and exponential backoff.
3. THE Deep_Dive_Document page 01 SHALL describe the Ingestion worker's adapter dispatch pattern, referencing the adapter classes (`PolygonMarketAdapter`, `PolygonNewsAdapter`, `SECEdgarAdapter`, `MacroNewsAdapter`) in `services/ingestion/`.
4. THE Deep_Dive_Document page 01 SHALL explain content deduplication via Redis content-hash markers (`stonks:dedupe:*` with 24-hour TTL) and raw artifact storage in MinIO buckets (`stonks-raw-market`, `stonks-raw-news`, `stonks-raw-filings`).
5. THE Deep_Dive_Document page 01 SHALL describe the Parser's role in converting raw HTML/text into normalized documents, including quality scoring with confidence levels (`high`, `medium`, `low`), company mention detection via alias matching, and the routing decision that sends `macro_event` documents to `stonks:queue:macro_classification` instead of `stonks:queue:extraction`.
6. THE Deep_Dive_Document page 01 SHALL be written in narrative prose style with explanatory paragraphs, not as a reference table or bullet-point list.
### Requirement 3: Page 2 — AI Agent Processing and Structured Extraction
**User Story:** As a technical reader, I want to understand how the AI agents process documents and produce structured JSON output, so that I can evaluate the extraction quality and understand the schema contract.
#### Acceptance Criteria
1. THE Deep_Dive_Document page 02 SHALL explain the Document Intelligence Extractor agent (`document-extractor` slug), including its entry point (`services/extractor/main.py``services/extractor/client.py`), the system prompt, and the user prompt template built by `build_extraction_prompt()` in `services/extractor/prompts.py`.
2. THE Deep_Dive_Document page 02 SHALL describe the `ExtractionResult` JSON schema with all fields (summary, companies array with ticker/sentiment/impact_score/impact_horizon/catalyst_type/key_facts/risks/evidence_spans, macro_themes, novelty_score, confidence, extraction_warnings), referencing `services/extractor/schemas.py`.
3. THE Deep_Dive_Document page 02 SHALL explain the Global Event Classifier agent (`event-classifier` slug), including its entry point (`services/extractor/event_classifier.py`), the `GlobalEvent` output schema with event_types/severity/affected_regions/affected_sectors/affected_commodities/estimated_duration/confidence, and the anti-hallucination rules that prevent classifying company-specific news as macro events.
4. THE Deep_Dive_Document page 02 SHALL describe the JSON repair pipeline (direct parse → markdown fence stripping → `json-repair` library fallback) and the structural plus semantic validation in `services/extractor/schemas.py`, including retry logic with exponential backoff.
5. THE Deep_Dive_Document page 02 SHALL explain the `AgentConfigResolver` mechanism (`services/shared/agent_config.py`) that enables hot-swapping models and prompts via the `ai_agents` and `agent_variants` database tables with a 60-second TTL cache.
6. THE Deep_Dive_Document page 02 SHALL describe how extraction results are persisted to `document_intelligence` (one row per document) and `document_impact_records` (one row per company mention), and how the extractor enqueues aggregation jobs to `stonks:queue:aggregation`.
7. THE Deep_Dive_Document page 02 SHALL be written in narrative prose style with explanatory paragraphs, not as a reference table or bullet-point list.
### Requirement 4: Page 3 — Signal Scoring and the WeightedSignal Abstraction
**User Story:** As a technical reader, I want to understand how raw extraction output gets transformed into weighted signals for decision making, so that I can reason about why certain documents influence trends more than others.
#### Acceptance Criteria
1. THE Deep_Dive_Document page 03 SHALL explain the `WeightedSignal` dataclass (`services/aggregation/scoring.py`) and the composite weight formula: `combined = gate × recency × credibility × (1 + novelty_bonus) × market_context_multiplier`.
2. THE Deep_Dive_Document page 03 SHALL describe each weight component in detail: confidence gate (threshold 0.2), recency decay (exponential half-life per window: intraday=2h, 1d=12h, 7d=72h, 30d=240h, 90d=720h), source credibility weighting (clamped [0.1, 1.0] with configurable exponent), novelty bonus (up to 25%), and market context multiplier (volatility boost up to 30%, volume surge boost 15%).
3. THE Deep_Dive_Document page 03 SHALL explain how sentiment labels are mapped to numeric values (+1.0 positive, -1.0 negative, 0.0 neutral/mixed) via `sentiment_to_numeric()` and how the weighted sentiment average is computed across all signals.
4. THE Deep_Dive_Document page 03 SHALL describe the three signal layers (Company, Macro, Competitive) and how each produces `WeightedSignal` objects that are concatenated into a single list before trend computation, with relative influence controlled by `MACRO_SIGNAL_WEIGHT` (0.3) and `COMPETITIVE_SIGNAL_WEIGHT` (0.2).
5. THE Deep_Dive_Document page 03 SHALL explain the runtime toggle mechanism for macro and competitive layers via the `risk_configs` database table, including graceful degradation when a layer is disabled or fails.
6. THE Deep_Dive_Document page 03 SHALL be written in narrative prose style with explanatory paragraphs, not as a reference table or bullet-point list.
### Requirement 5: Page 4 — Trend Aggregation and Accumulating Signals
**User Story:** As a technical reader, I want to understand how the aggregation engine merges multiple signals — including consecutive signals suggesting the same direction — to produce trend summaries that drive grander decisions, so that I can see how accumulating bearish or bullish evidence escalates the system's response.
#### Acceptance Criteria
1. THE Deep_Dive_Document page 04 SHALL explain how the Aggregation_Engine (`services/aggregation/worker.py`) computes `TrendSummary` objects across five time windows (intraday, 1d, 7d, 30d, 90d) by fetching impact records, macro impacts, and competitive signals for a ticker.
2. THE Deep_Dive_Document page 04 SHALL describe the trend direction derivation rules: bullish (avg_sentiment ≥ 0.15), bearish (avg_sentiment ≤ -0.15), mixed (contradiction > 0.10 and |avg_sentiment| < 0.30), neutral (otherwise), referencing `derive_trend_direction()` in `services/aggregation/worker.py`.
3. THE Deep_Dive_Document page 04 SHALL explain contradiction detection (`services/aggregation/contradiction.py`), including sentiment disagreement analysis and catalyst-level disagreement, and how the contradiction score (minority_weight / total_weight) penalizes trend confidence.
4. THE Deep_Dive_Document page 04 SHALL describe how consecutive signals in the same direction accumulate to strengthen trend_strength and confidence, explaining the evidence ranking mechanism (`rank_evidence()`) that uses composite scoring (weight, impact, recency, confidence) and the confidence computation that rewards unique source count (caps at 15 sources for 0.8 contribution) and signal agreement (log₂ scaling, saturates around 7 unique sources).
5. THE Deep_Dive_Document page 04 SHALL explain how accumulating bearish signals across multiple documents and time windows escalate the system's response — from a neutral hold to a bearish sell recommendation — and conversely how accumulating bullish signals escalate from watch to buy, using the trend strength and confidence thresholds from the eligibility rules.
6. THE Deep_Dive_Document page 04 SHALL describe trend projections (`services/aggregation/projection.py`), including macro decay, momentum, driving factors, and divergence detection.
7. THE Deep_Dive_Document page 04 SHALL describe persistence to `trend_windows` (upserted each cycle), `trend_history` (time-series snapshots), `trend_evidence` (per-document rankings), and `trend_projections`.
8. THE Deep_Dive_Document page 04 SHALL be written in narrative prose style with explanatory paragraphs, not as a reference table or bullet-point list.
### Requirement 6: Page 5 — Recommendation Generation and Signal-to-Action Translation
**User Story:** As a technical reader, I want to understand how trend summaries are translated into actionable recommendations with risk classification and thesis generation, so that I can see the decision logic between aggregated intelligence and trading actions.
#### Acceptance Criteria
1. THE Deep_Dive_Document page 05 SHALL explain the data quality suppression layer (`services/recommendation/suppression.py`), including the six suppression checks (extraction confidence < 0.40, evidence staleness > 168h, source diversity < 1, extraction failure rate > 50%, valid document count < 2, data quality score < 0.30) and the safety suppressions for macro-only and pattern-only trend shifts.
2. THE Deep_Dive_Document page 05 SHALL describe the eligibility evaluation (`services/recommendation/eligibility.py`), including gate checks (confidence ≥ 0.35, strength ≥ 0.10, contradiction ≤ 0.60, evidence ≥ 2, direction ≠ neutral), action mapping (BUY/SELL for strength ≥ 0.25, HOLD for weaker directional signals, WATCH otherwise), and mode escalation (informational → paper_eligible → live_eligible based on confidence and evidence thresholds).
3. THE Deep_Dive_Document page 05 SHALL explain position sizing computation from signal quality: base 1% + confidence × strength scaling up to 10%, with contradiction penalty, evidence count penalty, and max loss percentage scaling.
4. THE Deep_Dive_Document page 05 SHALL describe the two-layer thesis generation: deterministic thesis assembly from trend data, and optional LLM rewrite via the `thesis-rewriter` agent (`services/recommendation/thesis_llm.py`) for trading-eligible recommendations.
5. THE Deep_Dive_Document page 05 SHALL explain risk classification (low/moderate/high/very_high) based on contradiction score, confidence, evidence count, and mode.
6. THE Deep_Dive_Document page 05 SHALL describe persistence to `recommendations`, `recommendation_evidence`, and `risk_evaluations` tables.
7. THE Deep_Dive_Document page 05 SHALL be written in narrative prose style with explanatory paragraphs, not as a reference table or bullet-point list.
### Requirement 7: Page 6 — Trading Engine Decisions and Execution
**User Story:** As a technical reader, I want to understand how the trading engine uses aggregated trend data to make buy/sell/hold decisions, including position sizing, risk evaluation, and circuit breakers, so that I can trace any trade back to its intelligence origin.
#### Acceptance Criteria
1. THE Deep_Dive_Document page 06 SHALL explain the Trading_Engine decision loop (`services/trading/engine.py`), including the five concurrent async tasks: decision loop (60s polling), stop-loss monitor, performance loop, risk tier scheduler, and rebalance scheduler.
2. THE Deep_Dive_Document page 06 SHALL describe the pre-trade check sequence in order: circuit breaker check, trading window check, confidence gate (risk-tier minimum), deduplication, declining positions check, and max open positions check, explaining that the first failure short-circuits the evaluation.
3. THE Deep_Dive_Document page 06 SHALL explain position sizing (`services/trading/position_sizer.py`), including confidence-based scaling with sample-size-dampened agreement scoring, risk tier adjustment (conservative/moderate/aggressive with specific parameter differences), correlation-aware diversification, sector exposure reduction, earnings proximity adjustment, and the absolute position cap.
4. THE Deep_Dive_Document page 06 SHALL describe the Circuit_Breaker mechanism (`services/trading/circuit_breaker.py`), including the three trigger types (daily_loss with emergency drawdown threshold, single_position loss with ticker cooldown, volatility with stop-loss clustering detection), cooldown computation, and Redis state tracking (`stonks:trading:circuit_breaker:*`).
5. THE Deep_Dive_Document page 06 SHALL explain the reserve pool mechanism (`services/trading/reserve_pool.py`): profit siphoning (default 20%), high-water mark rebalancing (30% threshold), emergency liquidation, and ledger tracking in `reserve_pool_ledger`.
6. THE Deep_Dive_Document page 06 SHALL describe risk tier auto-adjustment (`services/trading/risk_tier_controller.py`), including the evaluation criteria (Sharpe ratio, drawdown, win rate) and the three tier configurations with their parameter differences (min confidence, max position %, stop-loss ATR multiplier, reward/risk ratio, max sector %, max portfolio heat).
7. THE Deep_Dive_Document page 06 SHALL explain the order submission flow: `TradingDecision` persistence to `trading_decisions`, order job enqueue to `stonks:queue:broker_orders`, broker adapter risk evaluation, Alpaca paper trading submission, and the full audit trail from signal to broker response.
8. THE Deep_Dive_Document page 06 SHALL be written in narrative prose style with explanatory paragraphs, not as a reference table or bullet-point list.
### Requirement 8: Mermaid Diagram Quality and Separation
**User Story:** As a technical reader, I want architecture diagrams in separate files that I can render independently, so that I can use them in presentations or embed them in other documents.
#### Acceptance Criteria
1. WHEN a Mermaid_Diagram_File is created, THE Deep_Dive_Document SHALL store the diagram in a standalone Markdown file under `docs/intelligence-pipeline-deep-dive/diagrams/` with a descriptive filename (e.g., `ingestion-to-extraction-flow.md`).
2. THE Deep_Dive_Document SHALL include at least 4 Mermaid_Diagram_Files: one for the ingestion-to-extraction pipeline, one for the three-layer signal merging, one for the recommendation generation flow, and one for the trading engine decision loop.
3. WHEN a Mermaid diagram references a service, THE Mermaid_Diagram_File SHALL label the service with both its human-readable name and its Python module path (e.g., `Extractor\nservices/extractor/main.py`).
4. WHEN a Mermaid diagram references a queue, THE Mermaid_Diagram_File SHALL use the full Redis key pattern (e.g., `stonks:queue:extraction`).
5. WHEN a Mermaid diagram references a database table, THE Mermaid_Diagram_File SHALL use the exact PostgreSQL table name.
### Requirement 9: Narrative Style and Cross-Referencing
**User Story:** As a technical reader, I want the document to read as a coherent narrative rather than a reference manual, so that I can build a mental model of the full pipeline without jumping between disconnected sections.
#### Acceptance Criteria
1. THE Deep_Dive_Document SHALL use narrative prose with explanatory paragraphs as the primary writing style, reserving tables and bullet lists for structured data summaries only.
2. WHEN a page references content covered in a different page, THE Deep_Dive_Document SHALL include a Markdown link to the relevant page and section.
3. THE Deep_Dive_Document SHALL include transitional paragraphs at the end of each page that preview what the next page covers, creating a continuous narrative flow.
4. THE Deep_Dive_Document SHALL reference the existing documentation where appropriate (e.g., `docs/services.md`, `docs/ai-agents.md`, `docs/architecture-data-pipeline.md`, `docs/llm-to-trade-pipeline.md`) for readers who want deeper reference-level detail.
5. IF a concept is introduced for the first time, THEN THE Deep_Dive_Document SHALL provide a brief inline explanation before using the concept in subsequent discussion.
### Requirement 10: Codebase Accuracy
**User Story:** As a developer, I want the document to reference actual code modules, database tables, and queue names from the codebase, so that I can use the document as a reliable guide when navigating the source code.
#### Acceptance Criteria
1. THE Deep_Dive_Document SHALL reference code modules using paths that exist in the repository (e.g., `services/aggregation/scoring.py`, `services/trading/circuit_breaker.py`, `services/shared/schemas.py`).
2. THE Deep_Dive_Document SHALL reference database tables using names that match the PostgreSQL schema as defined in `infra/migrations/`.
3. THE Deep_Dive_Document SHALL reference Redis queue names using the constants defined in `services/shared/redis_keys.py` (e.g., `QUEUE_EXTRACTION`, `QUEUE_AGGREGATION`, `QUEUE_RECOMMENDATION`, `QUEUE_BROKER`).
4. THE Deep_Dive_Document SHALL reference Pydantic schema classes using their actual class names from `services/shared/schemas.py` (e.g., `DocumentIntelligence`, `TrendSummary`, `Recommendation`, `GlobalEventSchema`, `CompanyImpact`).
5. THE Deep_Dive_Document SHALL reference configuration environment variables using the exact names defined in `services/shared/config.py` and the service-specific configuration sections.
@@ -0,0 +1,35 @@
# Tasks — Intelligence Pipeline Deep Dive
## Task 1: Create directory structure and index file
- [x] 1.1 Create `docs/intelligence-pipeline-deep-dive/` directory and `docs/intelligence-pipeline-deep-dive/diagrams/` subdirectory
- [x] 1.2 Create `docs/intelligence-pipeline-deep-dive/index.md` with table of contents linking to all 6 pages and all diagram files, plus references to existing docs (`docs/services.md`, `docs/ai-agents.md`, `docs/architecture-data-pipeline.md`, `docs/llm-to-trade-pipeline.md`)
## Task 2: Create Mermaid diagram files
- [x] 2.1 Create `docs/intelligence-pipeline-deep-dive/diagrams/ingestion-to-extraction-flow.md` — flowchart from Scheduler through Ingestion, Parser, to Extractor with all queues (`stonks:queue:ingestion`, `stonks:queue:parsing`, `stonks:queue:extraction`, `stonks:queue:macro_classification`), storage (MinIO buckets, PostgreSQL tables), and service module paths
- [x] 2.2 Create `docs/intelligence-pipeline-deep-dive/diagrams/three-layer-signal-merging.md` — flowchart showing Company signals (`document_impact_records`), Macro signals (`macro_impact_records`), and Competitive signals (`competitive_signal_records`) each producing `WeightedSignal` objects that merge into the Aggregation engine (`services/aggregation/worker.py`)
- [x] 2.3 Create `docs/intelligence-pipeline-deep-dive/diagrams/weighted-signal-computation.md` — diagram showing the composite weight formula components: confidence gate, recency decay, source credibility, novelty bonus, and market context multiplier
- [x] 2.4 Create `docs/intelligence-pipeline-deep-dive/diagrams/trend-accumulation-escalation.md` — diagram showing how consecutive signals accumulate across time windows to escalate from neutral → watch → hold → buy/sell decisions
- [x] 2.5 Create `docs/intelligence-pipeline-deep-dive/diagrams/recommendation-generation-flow.md` — flowchart from TrendSummary through data quality suppression, eligibility evaluation, thesis generation, risk classification, to recommendation persistence
- [x] 2.6 Create `docs/intelligence-pipeline-deep-dive/diagrams/trading-engine-decision-loop.md` — flowchart showing the pre-trade check sequence (circuit breaker → trading window → confidence gate → dedup → declining positions → max positions), position sizing, and order submission to `stonks:queue:broker_orders`
## Task 3: Write Page 1 — Data Ingestion and Preparation
- [x] 3.1 Write `docs/intelligence-pipeline-deep-dive/01-data-ingestion-and-preparation.md` covering: four input data categories (Polygon news, SEC EDGAR filings, Polygon market data, macro news APIs), Scheduler cadence polling (market_api: 300s, news_api: 300s, filings_api: 3600s, macro_news: 600s) with rate limiting and backoff, Ingestion worker adapter dispatch (`PolygonMarketAdapter`, `PolygonNewsAdapter`, `SECEdgarAdapter`, `MacroNewsAdapter`), content deduplication via Redis (`stonks:dedupe:*` with 24h TTL), raw artifact storage in MinIO (`stonks-raw-market`, `stonks-raw-news`, `stonks-raw-filings`), Parser role (HTML normalization, quality scoring, company mention detection, routing `macro_event` docs to `stonks:queue:macro_classification`). Written in narrative prose with links to diagrams and transition to Page 2.
## Task 4: Write Page 2 — AI Agent Processing and Structured Extraction
- [x] 4.1 Write `docs/intelligence-pipeline-deep-dive/02-ai-agent-processing-and-extraction.md` covering: Document Intelligence Extractor agent (`document-extractor` slug, `services/extractor/main.py``services/extractor/client.py`, system prompt, `build_extraction_prompt()` in `services/extractor/prompts.py`), `ExtractionResult` JSON schema with all fields, Global Event Classifier agent (`event-classifier` slug, `services/extractor/event_classifier.py`, `GlobalEvent` schema, anti-hallucination rules), JSON repair pipeline (direct parse → fence stripping → `json-repair` fallback), structural + semantic validation in `services/extractor/schemas.py`, `AgentConfigResolver` mechanism (`services/shared/agent_config.py`, `ai_agents`/`agent_variants` tables, 60s TTL cache), persistence to `document_intelligence` and `document_impact_records`, aggregation job enqueue. Written in narrative prose with links to diagrams and transition to Page 3.
## Task 5: Write Page 3 — Signal Scoring and the WeightedSignal Abstraction
- [x] 5.1 Write `docs/intelligence-pipeline-deep-dive/03-signal-scoring-and-weighted-signals.md` covering: `WeightedSignal` dataclass (`services/aggregation/scoring.py`), composite weight formula (`combined = gate × recency × credibility × (1 + novelty_bonus) × market_context_multiplier`), each component in detail (confidence gate threshold 0.2, recency decay half-lives per window, source credibility clamped [0.1, 1.0], novelty bonus up to 25%, market context volatility boost up to 30% and volume surge boost 15%), sentiment mapping via `sentiment_to_numeric()`, weighted sentiment average computation, three signal layers (Company, Macro weight 0.3, Competitive weight 0.2), runtime toggle via `risk_configs` table. Written in narrative prose with links to diagrams and transition to Page 4.
## Task 6: Write Page 4 — Trend Aggregation and Accumulating Signals
- [x] 6.1 Write `docs/intelligence-pipeline-deep-dive/04-trend-aggregation-and-accumulating-signals.md` covering: Aggregation engine computing TrendSummary across 5 windows (intraday, 1d, 7d, 30d, 90d), trend direction rules (bullish ≥ 0.15, bearish ≤ -0.15, mixed, neutral), contradiction detection (`services/aggregation/contradiction.py`, minority_weight/total_weight), evidence ranking (`rank_evidence()` composite scoring), confidence computation (unique source count caps at 15, log₂ scaling saturates at 7 sources), how consecutive same-direction signals accumulate to escalate decisions (neutral → watch → hold → buy/sell), trend projections (`services/aggregation/projection.py`, macro decay, momentum, divergence detection), persistence to `trend_windows`, `trend_history`, `trend_evidence`, `trend_projections`. Written in narrative prose with links to diagrams and transition to Page 5.
## Task 7: Write Page 5 — Recommendation Generation and Signal-to-Action Translation
- [x] 7.1 Write `docs/intelligence-pipeline-deep-dive/05-recommendation-generation.md` covering: data quality suppression (`services/recommendation/suppression.py`, 6 checks: extraction confidence < 0.40, staleness > 168h, source diversity < 1, failure rate > 50%, valid docs < 2, quality score < 0.30, plus macro-only and pattern-only safety), eligibility evaluation (`services/recommendation/eligibility.py`, gate checks, action mapping BUY/SELL/HOLD/WATCH, mode escalation informational/paper_eligible/live_eligible), position sizing (base 1% + confidence × strength up to 10%, contradiction and evidence penalties), thesis generation (deterministic + optional LLM rewrite via `thesis-rewriter` agent), risk classification (low/moderate/high/very_high), persistence to `recommendations`, `recommendation_evidence`, `risk_evaluations`. Written in narrative prose with links to diagrams and transition to Page 6.
## Task 8: Write Page 6 — Trading Engine Decisions and Execution
- [x] 8.1 Write `docs/intelligence-pipeline-deep-dive/06-trading-decisions-and-execution.md` covering: Trading engine decision loop (`services/trading/engine.py`, 5 concurrent tasks: decision loop 60s, stop-loss monitor, performance loop, risk tier scheduler, rebalance scheduler), pre-trade check sequence (circuit breaker → trading window → confidence gate → dedup → declining positions → max positions), position sizing (`services/trading/position_sizer.py`, confidence scaling, risk tier adjustment, correlation diversification, sector exposure, earnings proximity, absolute cap), circuit breaker (`services/trading/circuit_breaker.py`, daily_loss, single_position, volatility triggers, cooldown, Redis state), reserve pool (`services/trading/reserve_pool.py`, profit siphoning 20%, high-water mark 30%, emergency liquidation), risk tier auto-adjustment (`services/trading/risk_tier_controller.py`, Sharpe/drawdown/win-rate evaluation, conservative/moderate/aggressive tiers), order submission flow (TradingDecision → `stonks:queue:broker_orders` → broker adapter → Alpaca). Written in narrative prose with links to diagrams.
## Task 9: Update index and verify cross-references
- [x] 9.1 Update `docs/intelligence-pipeline-deep-dive/index.md` to ensure all page links and diagram links are correct and all files exist
- [x] 9.2 Verify all inter-page links within narrative pages resolve correctly and all diagram references point to existing files
@@ -0,0 +1 @@
{"specId": "a7e3f1b2-9c4d-4e8a-b5f6-d2a1c3e7f9b0", "workflowType": "requirements-first", "specType": "feature"}
+350
View File
@@ -0,0 +1,350 @@
# Design Document: Remote vLLM Support
## Overview
This design introduces an LLM provider abstraction layer into Stonks Oracle so that both the existing Ollama backend and a new remote vLLM backend can be used interchangeably for document extraction and event classification. The vLLM server at `http://192.168.42.254:8000` runs `RedHatAI/Qwen3.6-35B-A3B-NVFP4` on an NVIDIA RTX 5090 with tensor parallelism and exposes an OpenAI-compatible `/v1/chat/completions` API.
The design preserves full backward compatibility — existing Ollama deployments work without any configuration changes. Provider selection is driven by the existing `model_provider` column in the `ai_agents` and `agent_variants` database tables, requiring no new migrations.
## Architecture
```mermaid
graph TD
subgraph "Extractor Worker"
MAIN[main.py]
FACTORY[LLMClientFactory]
EXTRACT[Extraction Pipeline]
CLASSIFY[Event Classification Pipeline]
end
subgraph "Provider Abstraction"
PROTO[LLMClient Protocol]
OLLAMA_IMPL[OllamaClient]
VLLM_IMPL[VLLMClient]
end
subgraph "Configuration"
RESOLVER[AgentConfigResolver]
OLLAMA_CFG[OllamaConfig]
VLLM_CFG[VLLMConfig]
APP_CFG[AppConfig]
end
subgraph "External Services"
OLLAMA_SRV[Ollama Server<br/>:11434/api/chat]
VLLM_SRV[vLLM Server<br/>:8000/v1/chat/completions]
end
MAIN --> FACTORY
FACTORY --> PROTO
PROTO --> OLLAMA_IMPL
PROTO --> VLLM_IMPL
EXTRACT --> PROTO
CLASSIFY --> PROTO
RESOLVER --> FACTORY
OLLAMA_CFG --> FACTORY
VLLM_CFG --> FACTORY
APP_CFG --> OLLAMA_CFG
APP_CFG --> VLLM_CFG
OLLAMA_IMPL --> OLLAMA_SRV
VLLM_IMPL --> VLLM_SRV
```
The key architectural decision is to use a Python `Protocol` (structural typing) rather than an ABC for the LLM client interface. This allows the existing `OllamaClient` to satisfy the protocol without inheritance changes, maintaining backward compatibility. The `VLLMClient` is a new class that also satisfies the protocol.
A factory function in `services/extractor/llm_factory.py` takes a `ResolvedAgentConfig` and the base configs, returning the appropriate client. The extractor worker (`main.py`) uses this factory instead of directly constructing `OllamaClient`.
## Components and Interfaces
### 1. LLM Client Protocol (`services/shared/llm_protocol.py`)
A `typing.Protocol` defining the contract both clients must satisfy:
```python
from typing import Protocol, runtime_checkable
@runtime_checkable
class LLMClient(Protocol):
async def call_llm(
self,
prompts: dict[str, str],
json_schema: dict[str, object],
document_text: str = "",
) -> "ExtractionAttempt": ...
async def close(self) -> None: ...
```
The `call_llm` method signature matches the existing `OllamaClient._call_ollama()` parameters and return type. The `OllamaClient` gains a public `call_llm` method that delegates to `_call_ollama()`, preserving the private method for internal backward compatibility.
### 2. VLLMClient (`services/extractor/vllm_client.py`)
New client implementing the `LLMClient` protocol for the OpenAI-compatible API:
```python
@dataclass
class VLLMClient:
_config: VLLMConfig
_http: httpx.AsyncClient
_owns_client: bool
async def call_llm(
self,
prompts: dict[str, str],
json_schema: dict[str, object],
document_text: str = "",
) -> ExtractionAttempt: ...
async def close(self) -> None: ...
```
**Request format** (OpenAI-compatible):
```json
{
"model": "RedHatAI/Qwen3.6-35B-A3B-NVFP4",
"messages": [
{"role": "system", "content": "..."},
{"role": "user", "content": "..."}
],
"max_tokens": 4096,
"temperature": 0.7,
"response_format": {"type": "json_object"}
}
```
**Response parsing**: Extracts `choices[0].message.content`, then applies the same `_strip_markdown_fences()` and `_repair_json()` pipeline as `OllamaClient`.
**Error handling**: Maps HTTP errors to the same string format as `OllamaClient` (`timeout`, `http_{code}`, `connection_error: {details}`, `empty_model_response`), so the existing `_is_retryable()` function works without modification.
**Key differences from OllamaClient**:
- Endpoint: `/v1/chat/completions` instead of `/api/chat`
- No `think: false`, `stream: false`, or `options` block
- Uses `max_tokens` instead of `options.num_predict`
- Uses `response_format: {"type": "json_object"}` for structured output
- Supports `temperature` parameter (Ollama uses model defaults)
- Response in `choices[0].message.content` instead of `message.content`
### 3. VLLMConfig (`services/shared/config.py`)
New dataclass alongside `OllamaConfig`:
```python
@dataclass
class VLLMConfig:
base_url: str = "http://192.168.42.254:8000"
model: str = "RedHatAI/Qwen3.6-35B-A3B-NVFP4"
timeout: int = 120
max_retries: int = 2
retry_base_delay: float = 1.0
retry_max_delay: float = 10.0
retry_backoff_multiplier: float = 2.0
max_tokens: int = 32768
temperature: float = 0.7
api_key: str = "" # Optional, for authenticated vLLM deployments
```
Loaded from `VLLM_*` environment variables in `load_config()`. Added to `AppConfig` as `vllm: VLLMConfig`.
### 4. LLM Client Factory (`services/extractor/llm_factory.py`)
Factory function that replaces the hardcoded `OllamaClient` construction:
```python
def build_llm_client(
resolved: ResolvedAgentConfig | None,
ollama_config: OllamaConfig,
vllm_config: VLLMConfig,
http_client: httpx.AsyncClient | None = None,
) -> LLMClient:
"""Return the appropriate LLM client based on resolved provider."""
...
def build_config_from_resolved(
resolved: ResolvedAgentConfig,
base_ollama: OllamaConfig,
base_vllm: VLLMConfig,
) -> OllamaConfig | VLLMConfig:
"""Build provider-specific config from resolved agent config."""
...
```
Provider routing logic:
1. If `resolved` is `None` or `resolved.model_provider` is `"ollama"` or empty → `OllamaClient`
2. If `resolved.model_provider` is `"vllm"``VLLMClient`
3. Unknown provider → log warning, fall back to `OllamaClient`
### 5. Updated Extractor Worker (`services/extractor/main.py`)
Changes to `main()`:
- Replace `_build_ollama_config_from_resolved()` with `build_llm_client()` from the factory
- Store clients as `LLMClient` type instead of `OllamaClient`
- On config refresh (every 100 jobs), detect provider changes and swap clients
- Log provider switches at INFO level
Changes to `_process_macro_classification()`:
- Accept `LLMClient` instead of `OllamaClient` for the classifier parameter
### 6. Updated OllamaClient (`services/extractor/client.py`)
Minimal changes to satisfy the protocol:
- Add public `call_llm()` method that delegates to `_call_ollama()`
- Keep `_call_ollama()` as-is for backward compatibility
- The `extract()` method continues to call `_call_ollama()` internally
### 7. Updated Event Classifier (`services/extractor/event_classifier.py`)
Changes to `classify_global_event()`:
- Accept `LLMClient` instead of `Any` for the `ollama_client` parameter
- Call `client.call_llm()` instead of `ollama_client._call_ollama()`
- Set `ModelMetadata.provider` based on the actual client type (inspect `_config` or pass provider string)
### 8. Helm Values (`infra/helm/stonks-oracle/values.yaml`)
New config entries:
```yaml
config:
VLLM_BASE_URL: "http://192.168.42.254:8000"
VLLM_MODEL: "RedHatAI/Qwen3.6-35B-A3B-NVFP4"
VLLM_TIMEOUT: "120"
VLLM_MAX_RETRIES: "2"
VLLM_TEMPERATURE: "0.7"
VLLM_API_KEY: ""
```
### 9. Health Check (`services/extractor/vllm_client.py`)
Startup validation function:
```python
async def check_vllm_health(base_url: str, timeout: float = 10.0) -> bool:
"""GET {base_url}/v1/models to verify vLLM is reachable."""
...
```
Called from `main()` when the resolved or default config specifies vLLM. On failure, logs WARNING and falls back to Ollama. On success, logs INFO with server URL and model list.
## Data Models
### VLLMConfig Dataclass
| Field | Type | Default | Env Var |
|-------|------|---------|---------|
| `base_url` | `str` | `http://192.168.42.254:8000` | `VLLM_BASE_URL` |
| `model` | `str` | `RedHatAI/Qwen3.6-35B-A3B-NVFP4` | `VLLM_MODEL` |
| `timeout` | `int` | `120` | `VLLM_TIMEOUT` |
| `max_retries` | `int` | `2` | `VLLM_MAX_RETRIES` |
| `retry_base_delay` | `float` | `1.0` | `VLLM_RETRY_BASE_DELAY` |
| `retry_max_delay` | `float` | `10.0` | `VLLM_RETRY_MAX_DELAY` |
| `retry_backoff_multiplier` | `float` | `2.0` | `VLLM_RETRY_BACKOFF_MULTIPLIER` |
| `max_tokens` | `int` | `32768` | `VLLM_MAX_TOKENS` |
| `temperature` | `float` | `0.7` | `VLLM_TEMPERATURE` |
| `api_key` | `str` | `""` | `VLLM_API_KEY` |
### ExtractionAttempt (unchanged)
The existing `ExtractionAttempt` dataclass is reused as-is for both providers. No changes needed.
### ModelMetadata (unchanged structure, new values)
The `provider` field now accepts `"vllm"` in addition to `"ollama"`. No schema change needed.
## Error Handling
### Error String Format Parity
Both clients produce identical error string formats so `_is_retryable()` works unchanged:
| Condition | Error String | Retryable |
|-----------|-------------|-----------|
| HTTP timeout | `timeout` | Yes |
| HTTP 400/401/403/404/422 | `http_{code}` | No |
| HTTP 500/502/503/429 | `http_{code}` | Yes |
| Connection refused/reset | `connection_error: {details}` | Yes |
| Empty response body | `empty_model_response` | Yes |
| Invalid JSON in response | `invalid_response_json` | Yes |
### Health Check Failure
If the vLLM health check fails at startup:
1. Log WARNING with the error details
2. Fall back to `OllamaClient` using `OllamaConfig`
3. Continue operation — the system degrades gracefully rather than crashing
### Provider Switch During Refresh
When the config refresh (every 100 jobs) detects a provider change:
1. Close the old client (`await old_client.close()`)
2. Construct the new client via the factory
3. Log the switch at INFO level
4. If new client construction fails, keep the old client and log ERROR
## Testing Strategy
### Property-Based Tests (`tests/test_pbt_llm_provider.py`)
Property-based tests using Hypothesis to verify the provider abstraction:
**P1: Provider factory routing property** (Req 3.4, 3.5, 9.5)
For all `model_provider` values in `{"ollama", "vllm", "", None}`, the factory returns the correct client type. For `"ollama"`, empty, or `None`, returns `OllamaClient`. For `"vllm"`, returns `VLLMClient`.
**P2: Error string format consistency property** (Req 5.6)
For all HTTP status codes (100-599), both `OllamaClient` and `VLLMClient` produce error strings in the same format (`http_{code}`), and `_is_retryable()` returns the same result for both.
**P3: VLLMClient request payload structure property** (Req 2.1, 8.1)
For all generated prompt dicts (system + user messages of arbitrary text), the VLLMClient produces a request payload that: contains `model`, `messages`, `max_tokens`, `temperature`; does NOT contain `think`, `stream`, `options`, `num_ctx`, `num_predict`.
**P4: JSON repair idempotence property** (Req 2.4)
For all valid JSON strings, `_repair_json(json_str)` returns a string that `json.loads()` can parse, and `_repair_json(_repair_json(json_str)) == _repair_json(json_str)` (idempotence).
**P5: Markdown fence stripping round-trip property** (Req 2.3)
For all strings `s`, `_strip_markdown_fences(f"```json\n{s}\n```")` returns `s` (stripped), and `_strip_markdown_fences(s)` returns `s` when no fences are present (identity).
**P6: VLLMConfig default construction property** (Req 3.1)
For all VLLMConfig instances constructed with default values, `base_url` is non-empty, `timeout > 0`, `max_retries >= 0`, `temperature` is between 0.0 and 2.0, and `max_tokens > 0`.
### Unit Tests (`tests/test_vllm_client.py`)
Example-based tests for specific behaviors:
- VLLMClient sends correct payload to `/v1/chat/completions` (mock httpx)
- VLLMClient extracts content from `choices[0].message.content`
- VLLMClient handles empty choices array → `empty_model_response`
- VLLMClient handles timeout → `timeout` error
- VLLMClient handles HTTP 500 → `http_500` error, retryable
- VLLMClient handles HTTP 400 → `http_400` error, non-retryable
- VLLMClient handles connection refused → `connection_error: ...`
- VLLMClient applies markdown fence stripping
- VLLMClient applies JSON repair
- VLLMClient includes temperature in payload
- VLLMClient includes `response_format` in payload
- Health check success logs INFO
- Health check failure logs WARNING and returns False
- Factory returns OllamaClient for provider="ollama"
- Factory returns VLLMClient for provider="vllm"
- Factory returns OllamaClient for provider="" (default)
- Factory returns OllamaClient for unknown provider with warning
- VLLMConfig loads from environment variables
- AppConfig includes vllm field with defaults
- OllamaClient.call_llm() delegates to _call_ollama()
### Existing Tests (unchanged)
- `tests/test_ollama_client.py` — continues to pass without modification
- All other existing test files — unaffected
## File Changes Summary
| File | Change Type | Description |
|------|-------------|-------------|
| `services/shared/llm_protocol.py` | **New** | `LLMClient` Protocol definition |
| `services/extractor/vllm_client.py` | **New** | `VLLMClient` implementation + health check |
| `services/extractor/llm_factory.py` | **New** | Factory function for provider routing |
| `services/shared/config.py` | **Modified** | Add `VLLMConfig`, update `AppConfig`, update `load_config()` |
| `services/extractor/client.py` | **Modified** | Add `call_llm()` public method to `OllamaClient` |
| `services/extractor/event_classifier.py` | **Modified** | Use `call_llm()` instead of `_call_ollama()`, accept `LLMClient` type |
| `services/extractor/main.py` | **Modified** | Use factory, support provider switching, health check |
| `infra/helm/stonks-oracle/values.yaml` | **Modified** | Add `VLLM_*` config entries |
| `tests/test_pbt_llm_provider.py` | **New** | Property-based tests for provider abstraction |
| `tests/test_vllm_client.py` | **New** | Unit tests for VLLMClient and factory |
@@ -0,0 +1,136 @@
# Requirements Document
## Introduction
Add remote vLLM support to the Stonks Oracle platform. The system currently uses Ollama exclusively for LLM inference via the `/api/chat` endpoint. A remote vLLM server running `RedHatAI/Qwen3.6-35B-A3B-NVFP4` on a 5090 GPU with tensor parallelism is available at `http://192.168.42.254:8000` and exposes an OpenAI-compatible `/v1/chat/completions` API. This feature introduces a provider abstraction layer so that both Ollama and vLLM backends can be used interchangeably, selected per-agent via the existing `model_provider` database column and environment variable configuration. The abstraction preserves all existing behavior (retry logic, JSON repair, audit trail, backoff, context window override) while adapting to the differences between the two API protocols.
## Glossary
- **LLM_Client**: An abstract interface defining the contract for sending chat completion requests to any LLM backend. Concrete implementations exist for Ollama and vLLM.
- **Ollama_Backend**: The existing Ollama inference server at `ollama.ollama-service.svc.cluster.local:11434` (cluster) or `http://10.1.1.12:2701` (external), using the `/api/chat` endpoint with Ollama-specific payload fields (`think`, `options.num_ctx`, `options.num_predict`).
- **VLLM_Backend**: A remote vLLM inference server at `http://192.168.42.254:8000` exposing the OpenAI-compatible `/v1/chat/completions` endpoint. Runs `RedHatAI/Qwen3.6-35B-A3B-NVFP4` on a 5090 GPU with tensor parallelism.
- **Provider**: A string identifier (`ollama` or `vllm`) that determines which LLM_Client implementation is used for a given agent. Stored in the `model_provider` column of `ai_agents` and `agent_variants` tables.
- **LLM_Config**: A provider-agnostic configuration dataclass containing connection and inference parameters (base_url, model, timeout, retries, max_tokens, context_window) used to construct an LLM_Client.
- **Extraction_Pipeline**: The document intelligence extraction workflow in `services/extractor/client.py` that sends documents to an LLM and parses structured JSON responses.
- **Event_Classification_Pipeline**: The macro event classification workflow in `services/extractor/event_classifier.py` that classifies global news articles via an LLM.
- **Agent_Config_Resolver**: The `AgentConfigResolver` in `services/shared/agent_config.py` that resolves runtime configuration from the `ai_agents` and `agent_variants` database tables, including the `model_provider` field.
- **OpenAI_Chat_Format**: The request/response format used by `/v1/chat/completions` — messages array with role/content, `max_tokens`, `temperature`, and response in `choices[0].message.content`.
- **JSON_Repair**: The existing `json-repair` library usage that fixes malformed JSON from model output, applied regardless of provider.
- **Model_Metadata**: The `ModelMetadata` Pydantic model in `services/shared/schemas.py` that tracks `provider`, `model_name`, `prompt_version`, and `schema_version` for audit.
## Requirements
### Requirement 1: Provider Abstraction Layer
**User Story:** As a developer, I want a provider abstraction layer that decouples LLM inference from any specific backend, so that the extraction and classification pipelines can use either Ollama or vLLM without code changes in the calling services.
#### Acceptance Criteria
1. THE LLM_Client interface SHALL define an async method that accepts a messages list (system and user prompts), a JSON schema hint, and optional document text, and returns an attempt result containing raw output, validation report, error string, duration, and model name.
2. THE LLM_Client interface SHALL define an async `close` method for releasing underlying HTTP resources.
3. WHEN the Extraction_Pipeline calls the LLM, THE Extraction_Pipeline SHALL use the LLM_Client interface instead of calling Ollama-specific endpoints directly.
4. WHEN the Event_Classification_Pipeline calls the LLM, THE Event_Classification_Pipeline SHALL use the LLM_Client interface instead of calling `_call_ollama()` directly.
5. THE Ollama_Backend implementation of LLM_Client SHALL preserve the existing `/api/chat` payload structure including `think: false`, `stream: false`, `options.num_predict`, and `options.num_ctx`.
6. THE VLLM_Backend implementation of LLM_Client SHALL send requests to `/v1/chat/completions` using the OpenAI_Chat_Format with `model`, `messages`, `max_tokens`, and `temperature` fields.
7. FOR ALL valid prompt inputs, sending a prompt through the Ollama_Backend and parsing the response SHALL produce the same ExtractionAttempt structure as the current `_call_ollama()` method (round-trip equivalence with existing behavior).
### Requirement 2: vLLM Client Implementation
**User Story:** As a developer, I want a vLLM client that communicates with the remote vLLM server using the OpenAI-compatible API, so that the platform can leverage the 5090 GPU for inference.
#### Acceptance Criteria
1. THE VLLM_Backend SHALL send POST requests to `{base_url}/v1/chat/completions` with a JSON payload containing `model`, `messages` (array of role/content objects), `max_tokens`, and `temperature`.
2. THE VLLM_Backend SHALL extract the response content from `choices[0].message.content` in the OpenAI-compatible response format.
3. THE VLLM_Backend SHALL apply the same markdown fence stripping logic as the Ollama_Backend to handle model output wrapped in ```json ... ``` blocks.
4. THE VLLM_Backend SHALL apply the same JSON_Repair logic as the Ollama_Backend to fix malformed JSON in model output.
5. WHEN the vLLM server returns an HTTP timeout, THE VLLM_Backend SHALL report the error as `timeout` in the attempt result, consistent with the Ollama_Backend error format.
6. WHEN the vLLM server returns an HTTP error status, THE VLLM_Backend SHALL report the error as `http_{status_code}` in the attempt result, consistent with the Ollama_Backend error format.
7. WHEN the vLLM server returns an empty `choices` array or missing `content`, THE VLLM_Backend SHALL report the error as `empty_model_response`.
8. IF the vLLM server is unreachable, THEN THE VLLM_Backend SHALL report the error as `connection_error: {details}`, consistent with the Ollama_Backend error format.
9. THE VLLM_Backend SHALL use the same `httpx.AsyncClient` timeout configuration as the Ollama_Backend, derived from the LLM_Config timeout value.
10. THE VLLM_Backend SHALL support an optional `temperature` parameter from the resolved agent config, defaulting to 0.7 when not specified.
### Requirement 3: Provider-Aware Configuration
**User Story:** As an operator, I want to configure the vLLM backend via environment variables and database agent config, so that I can switch providers without code changes.
#### Acceptance Criteria
1. THE Configuration SHALL include a `VLLMConfig` dataclass with fields: `base_url` (default `http://192.168.42.254:8000`), `model` (default `RedHatAI/Qwen3.6-35B-A3B-NVFP4`), `timeout` (default 120), `max_retries` (default 2), `retry_base_delay`, `retry_max_delay`, `retry_backoff_multiplier`, `max_tokens` (default 32768), and `temperature` (default 0.7).
2. THE Configuration SHALL load VLLMConfig values from environment variables prefixed with `VLLM_` (e.g., `VLLM_BASE_URL`, `VLLM_MODEL`, `VLLM_TIMEOUT`), following the same pattern as OllamaConfig.
3. THE AppConfig dataclass SHALL include a `vllm` field of type VLLMConfig alongside the existing `ollama` field.
4. WHEN the Agent_Config_Resolver resolves a `model_provider` value of `vllm`, THE service SHALL use the VLLMConfig base_url and construct a VLLM_Backend client instead of an Ollama_Backend client.
5. WHEN the Agent_Config_Resolver resolves a `model_provider` value of `ollama` or when no `model_provider` is specified, THE service SHALL continue to use the OllamaConfig and Ollama_Backend client as the default.
6. THE `_build_ollama_config_from_resolved` function in `services/extractor/main.py` SHALL be generalized to a provider-aware factory that returns the appropriate config and client type based on the resolved `model_provider`.
### Requirement 4: Provider Selection in Extractor Worker
**User Story:** As a developer, I want the extractor worker to select the correct LLM client based on the resolved agent config provider, so that each agent can independently use Ollama or vLLM.
#### Acceptance Criteria
1. WHEN the extractor worker starts, THE worker SHALL construct the default LLM_Client based on the environment variable configuration (defaulting to Ollama_Backend).
2. WHEN the Agent_Config_Resolver returns a resolved config with `model_provider = "vllm"` for the `document-extractor` slug, THE worker SHALL construct a VLLM_Backend client using the VLLMConfig base_url and the resolved model_name.
3. WHEN the Agent_Config_Resolver returns a resolved config with `model_provider = "vllm"` for the `event-classifier` slug, THE worker SHALL construct a VLLM_Backend client for the event classification pipeline.
4. WHEN the resolved config changes provider during a config refresh cycle (every 100 jobs), THE worker SHALL close the old LLM_Client and construct a new one matching the updated provider.
5. WHEN the resolved config changes from `ollama` to `vllm` or vice versa, THE worker SHALL log the provider switch at INFO level including the old and new provider, model name, and variant ID.
### Requirement 5: Retry and Error Handling Parity
**User Story:** As a developer, I want the vLLM client to use the same retry logic, backoff strategy, and error classification as the Ollama client, so that reliability behavior is consistent across providers.
#### Acceptance Criteria
1. THE VLLM_Backend SHALL use the same exponential backoff computation as the Ollama_Backend, using `retry_base_delay`, `retry_max_delay`, and `retry_backoff_multiplier` from the LLM_Config.
2. THE VLLM_Backend SHALL classify HTTP 400, 401, 403, 404, and 422 errors as non-retryable, consistent with the Ollama_Backend.
3. THE VLLM_Backend SHALL classify HTTP 500, 502, 503, 429, timeout, and connection errors as retryable, consistent with the Ollama_Backend.
4. WHEN the VLLM_Backend encounters a retryable error, THE Extraction_Pipeline SHALL retry up to `max_retries` times with exponential backoff, preserving each attempt in the audit trail.
5. WHEN the VLLM_Backend encounters a non-retryable error, THE Extraction_Pipeline SHALL stop retries immediately and record the attempt as non-retryable.
6. FOR ALL error types, the VLLM_Backend error string format SHALL match the Ollama_Backend error string format so that `_is_retryable()` works without modification.
### Requirement 6: Audit Trail and Model Metadata
**User Story:** As a developer, I want the audit trail and model metadata to correctly reflect which provider and model were used for each extraction, so that I can trace results back to the specific backend.
#### Acceptance Criteria
1. WHEN the VLLM_Backend completes an extraction attempt, THE attempt record SHALL include the vLLM model name in the `model` field.
2. WHEN an extraction or classification succeeds via the VLLM_Backend, THE Model_Metadata in the result SHALL have `provider` set to `"vllm"` and `model_name` set to the vLLM model identifier.
3. WHEN the `agent_performance_log` records an invocation that used the VLLM_Backend, THE log entry SHALL be attributed to the correct agent_id and variant_id, consistent with Ollama_Backend logging.
4. THE MinIO prompt and result artifacts persisted by the Event_Classification_Pipeline SHALL include the provider name and model name in the stored JSON, regardless of which backend was used.
### Requirement 7: Health Check and Connectivity Validation
**User Story:** As an operator, I want the system to validate connectivity to the vLLM server at startup, so that misconfiguration is detected early rather than failing silently on the first inference request.
#### Acceptance Criteria
1. WHEN the extractor worker starts and the resolved or default config specifies `model_provider = "vllm"`, THE worker SHALL send a GET request to `{vllm_base_url}/v1/models` to verify the vLLM server is reachable.
2. IF the vLLM health check fails at startup, THEN THE worker SHALL log a WARNING and fall back to the Ollama_Backend, continuing operation with degraded capability.
3. IF the vLLM health check succeeds, THEN THE worker SHALL log an INFO message confirming the vLLM connection including the server URL and available model name.
4. THE health check SHALL use a timeout of 10 seconds to avoid blocking worker startup on an unresponsive server.
### Requirement 8: Context Window and Token Handling for vLLM
**User Story:** As a developer, I want the vLLM client to handle context window and token limits appropriately for the vLLM API, so that large documents are processed correctly on the remote GPU.
#### Acceptance Criteria
1. WHEN the resolved agent config specifies a non-zero `context_window`, THE VLLM_Backend SHALL omit the `num_ctx` Ollama-specific option and instead rely on the vLLM server's model configuration for context window sizing.
2. THE VLLM_Backend SHALL pass `max_tokens` in the OpenAI-compatible request payload to control the maximum number of output tokens generated.
3. WHEN the resolved agent config specifies a non-zero `input_token_limit`, THE Extraction_Pipeline SHALL truncate the input text before sending it to the VLLM_Backend, using the same truncation logic as for the Ollama_Backend.
4. WHEN the resolved agent config specifies a non-zero `token_budget`, THE worker SHALL enforce the same hourly token budget check for vLLM invocations as for Ollama invocations.
### Requirement 9: Backward Compatibility
**User Story:** As a developer, I want the vLLM integration to be fully backward compatible, so that existing Ollama-based deployments continue to work without any configuration changes.
#### Acceptance Criteria
1. WHEN no `VLLM_BASE_URL` environment variable is set and no agent config specifies `model_provider = "vllm"`, THE system SHALL behave identically to the current Ollama-only implementation.
2. THE existing `OllamaConfig` dataclass and its environment variable loading SHALL remain unchanged.
3. THE existing `OllamaClient` class SHALL continue to function for Ollama-specific usage, with the LLM_Client interface added as a compatible layer on top.
4. THE existing test suite in `tests/test_ollama_client.py` SHALL continue to pass without modification.
5. WHEN the `model_provider` column in `ai_agents` or `agent_variants` contains `"ollama"` or NULL, THE system SHALL use the Ollama_Backend, preserving current behavior.
6. THE database migration for this feature SHALL NOT alter existing table structures; it SHALL only add new columns or tables if needed.
+82
View File
@@ -0,0 +1,82 @@
# Tasks
## Task 1: LLM Client Protocol and VLLMConfig
- [x] 1.1 Create `services/shared/llm_protocol.py` with `LLMClient` Protocol defining `call_llm(prompts, json_schema, document_text) -> ExtractionAttempt` and `close()` methods
- [x] 1.2 Add `VLLMConfig` dataclass to `services/shared/config.py` with fields: `base_url`, `model`, `timeout`, `max_retries`, `retry_base_delay`, `retry_max_delay`, `retry_backoff_multiplier`, `max_tokens`, `temperature`, `api_key`
- [x] 1.3 Add `vllm: VLLMConfig` field to `AppConfig` dataclass
- [x] 1.4 Add `VLLM_*` environment variable loading to `load_config()` function
- [x] 1.5 Add public `call_llm()` method to `OllamaClient` in `services/extractor/client.py` that delegates to `_call_ollama()`
## Task 2: VLLMClient Implementation
- [x] 2.1 Create `services/extractor/vllm_client.py` with `VLLMClient` class that satisfies the `LLMClient` protocol
- [x] 2.2 Implement `call_llm()` method that sends POST to `/v1/chat/completions` with OpenAI-compatible payload (`model`, `messages`, `max_tokens`, `temperature`, `response_format`)
- [x] 2.3 Implement response parsing: extract content from `choices[0].message.content`, apply `_strip_markdown_fences()` and `_repair_json()`
- [x] 2.4 Implement error handling: map timeout → `timeout`, HTTP errors → `http_{code}`, connection errors → `connection_error: {details}`, empty response → `empty_model_response`
- [x] 2.5 Implement `close()` method to release the underlying `httpx.AsyncClient`
- [x] 2.6 Implement `check_vllm_health(base_url, timeout=10.0)` async function that GETs `/v1/models` and returns bool
## Task 3: LLM Client Factory
- [x] 3.1 Create `services/extractor/llm_factory.py` with `build_llm_client()` function that returns `OllamaClient` or `VLLMClient` based on resolved `model_provider`
- [x] 3.2 Implement `build_config_from_resolved()` function that creates provider-specific config from `ResolvedAgentConfig` and base configs
- [x] 3.3 Handle unknown provider values: log warning and fall back to `OllamaClient`
## Task 4: Update Extractor Worker for Provider Abstraction
- [x] 4.1 Update `services/extractor/main.py` to import and use `build_llm_client()` from the factory instead of directly constructing `OllamaClient`
- [x] 4.2 Replace `_build_ollama_config_from_resolved()` usage with the factory's `build_config_from_resolved()` for both extractor and classifier clients
- [x] 4.3 Add vLLM health check call at startup when resolved config specifies `model_provider = "vllm"`, with fallback to Ollama on failure
- [x] 4.4 Update config refresh logic (every 100 jobs) to detect provider changes, close old client, and construct new client via factory
- [x] 4.5 Add INFO-level logging for provider switches including old/new provider, model name, and variant ID
## Task 5: Update Event Classifier for Provider Abstraction
- [x] 5.1 Update `classify_global_event()` in `services/extractor/event_classifier.py` to accept `LLMClient` protocol type instead of `Any` for the client parameter
- [x] 5.2 Replace `ollama_client._call_ollama()` calls with `client.call_llm()` calls
- [x] 5.3 Update `ModelMetadata.provider` assignment to use the actual provider string from the client (detect from config type or pass explicitly)
- [x] 5.4 Update retry logic to use client config attributes instead of accessing `ollama_client._base_delay` and `ollama_client._backoff_multiplier` directly
## Task 6: Helm Configuration
- [x] 6.1 Add `VLLM_BASE_URL`, `VLLM_MODEL`, `VLLM_TIMEOUT`, `VLLM_MAX_RETRIES`, `VLLM_TEMPERATURE`, and `VLLM_API_KEY` entries to the `config:` section in `infra/helm/stonks-oracle/values.yaml`
## Task 7: Unit Tests for VLLMClient
- [x] 7.1 Create `tests/test_vllm_client.py` with test for VLLMClient sending correct payload to `/v1/chat/completions` using mock httpx transport
- [x] 7.2 Add test for VLLMClient extracting content from `choices[0].message.content`
- [x] 7.3 Add test for VLLMClient handling empty choices array returning `empty_model_response` error
- [x] 7.4 Add test for VLLMClient handling HTTP timeout returning `timeout` error
- [x] 7.5 Add test for VLLMClient handling HTTP 500 returning `http_500` retryable error
- [x] 7.6 Add test for VLLMClient handling HTTP 400 returning `http_400` non-retryable error
- [x] 7.7 Add test for VLLMClient handling connection error returning `connection_error: ...`
- [x] 7.8 Add test for VLLMClient applying markdown fence stripping and JSON repair to response
- [x] 7.9 Add test for VLLMClient including temperature and response_format in payload
- [x] 7.10 Add test for health check success returning True and logging INFO
- [x] 7.11 Add test for health check failure returning False and logging WARNING
- [x] 7.12 Add test for OllamaClient.call_llm() delegating to _call_ollama()
- [x] 7.13 Add test for VLLMConfig loading from environment variables
- [x] 7.14 Add test for AppConfig including vllm field with correct defaults
## Task 8: Unit Tests for LLM Factory
- [x] 8.1 Add tests to `tests/test_vllm_client.py` for factory returning OllamaClient when provider is "ollama"
- [x] 8.2 Add test for factory returning VLLMClient when provider is "vllm"
- [x] 8.3 Add test for factory returning OllamaClient when provider is empty string (default)
- [x] 8.4 Add test for factory returning OllamaClient with warning when provider is unknown value
## Task 9: Property-Based Tests
- [x] 9.1 Create `tests/test_pbt_llm_provider.py` with property test for factory routing: for all model_provider in {"ollama", "vllm", "", None}, factory returns correct client type [PBT]
- [x] 9.2 Add property test for error string format consistency: for all HTTP status codes (100-599), `_is_retryable()` classifies them consistently [PBT]
- [x] 9.3 Add property test for VLLMClient request payload structure: for all generated prompt dicts, payload contains required OpenAI fields and excludes Ollama-specific fields [PBT]
- [x] 9.4 Add property test for JSON repair idempotence: for all valid JSON strings, `_repair_json()` is idempotent [PBT]
- [x] 9.5 Add property test for markdown fence stripping: for all strings, wrapping in fences then stripping recovers the original [PBT]
- [x] 9.6 Add property test for VLLMConfig defaults: for all default-constructed instances, invariants hold (timeout > 0, max_retries >= 0, 0 <= temperature <= 2, max_tokens > 0) [PBT]
## Task 10: Verification and Backward Compatibility
- [x] 10.1 Run existing `tests/test_ollama_client.py` to verify no regressions
- [x] 10.2 Run `ruff check services/` to verify no lint errors in modified files
- [x] 10.3 Run full test suite `python -m pytest tests/ -x --tb=short -q` to verify all tests pass
@@ -0,0 +1 @@
{"specId": "e6d189b2-5861-4e24-954f-5e254246a910", "workflowType": "requirements-first", "specType": "feature"}
@@ -0,0 +1,341 @@
# Design Document: Sanitized Pipeline Documentation
## Overview
This design specifies the process and structure for producing a sanitized version of the 6-page intelligence pipeline deep dive documentation. The sanitized docs transform the existing `docs/intelligence-pipeline-deep-dive/` content into domain-neutral equivalents stored at `docs/sanitized-pipeline-deep-dive/`, stripping all financial, market, and trading language while preserving every engineering detail — algorithms, formulas, architectural patterns, queue topologies, database schemas, code module references, and Mermaid diagrams.
The deliverable is a documentation-only transformation. No application code, database schemas, or infrastructure changes are involved. The output is Markdown files and Mermaid diagram files that mirror the original structure with domain-neutral framing.
**Key design decision**: The sanitization is a manual content transformation guided by a defined terminology map. Each source file is read, transformed according to the mapping rules, and written to the output directory. The original files remain untouched.
### Source Material
The source documentation at `docs/intelligence-pipeline-deep-dive/` consists of:
| File | Content |
|------|---------|
| `index.md` | Table of contents, introduction, diagram links, related docs |
| `01-data-ingestion-and-preparation.md` | Scheduler, ingestion worker, deduplication, parser |
| `02-ai-agent-processing-and-extraction.md` | Document extractor, event classifier, JSON repair, validation |
| `03-signal-scoring-and-weighted-signals.md` | Composite weight formula, three signal layers, sentiment mapping |
| `04-trend-aggregation-and-accumulating-signals.md` | Time windows, trend direction, contradiction, evidence ranking, confidence |
| `05-recommendation-generation.md` | Suppression, eligibility, position sizing, thesis, risk classification |
| `06-trading-decisions-and-execution.md` | Trading engine, pre-trade checks, circuit breakers, broker adapter |
| `diagrams/ingestion-to-extraction-flow.md` | Mermaid flowchart: scheduler → ingestion → parser → extractor |
| `diagrams/three-layer-signal-merging.md` | Mermaid flowchart: three signal layers → aggregation |
| `diagrams/weighted-signal-computation.md` | Mermaid flowchart: composite weight formula breakdown |
| `diagrams/trend-accumulation-escalation.md` | Mermaid flowchart: time windows → escalation path |
| `diagrams/recommendation-generation-flow.md` | Mermaid flowchart: suppression → eligibility → thesis → risk |
| `diagrams/trading-engine-decision-loop.md` | Mermaid flowchart: pre-trade checks → position sizing → order submission |
## Architecture
### Output File Organization
The sanitized docs mirror the source structure with sanitized filenames:
```
docs/sanitized-pipeline-deep-dive/
├── index.md
├── 01-data-ingestion-and-preparation.md
├── 02-ai-agent-processing-and-extraction.md
├── 03-signal-scoring-and-weighted-signals.md
├── 04-trend-aggregation-and-accumulating-signals.md
├── 05-recommendation-generation.md
├── 06-decision-execution.md
└── diagrams/
├── ingestion-to-extraction-flow.md
├── three-layer-signal-merging.md
├── weighted-signal-computation.md
├── trend-accumulation-escalation.md
├── recommendation-generation-flow.md
└── decision-engine-loop.md
```
**Filename changes from source:**
- `06-trading-decisions-and-execution.md``06-decision-execution.md` (removes "trading")
- `diagrams/trading-engine-decision-loop.md``diagrams/decision-engine-loop.md` (removes "trading")
- All other filenames are already domain-neutral and remain unchanged
### Transformation Process
The sanitization follows a three-pass approach for each file:
1. **Terminology pass**: Apply the terminology map to replace all financial/trading terms with domain-neutral equivalents. This covers inline text, headings, table cells, code blocks, and Mermaid diagram labels.
2. **Reference pass**: Update all internal cross-references to point to sanitized filenames (e.g., `06-trading-decisions-and-execution.md``06-decision-execution.md`, `trading-engine-decision-loop.md``decision-engine-loop.md`). Remove or neutralize references to external financial docs (e.g., links to `../llm-to-trade-pipeline.md` become neutral descriptions).
3. **Narrative pass**: Reframe example scenarios, inline illustrations, and narrative framing to use domain-neutral language. This pass handles context-dependent replacements that a simple find-and-replace cannot catch — e.g., "a bearish article about AAPL" becomes "a negative-sentiment article about Entity-A".
### Content Flow
The sanitized docs preserve the same page-to-page narrative flow as the originals:
```mermaid
flowchart LR
P1["Page 1\nData Ingestion"] --> P2["Page 2\nAI Extraction"]
P2 --> P3["Page 3\nSignal Scoring"]
P3 --> P4["Page 4\nTrend Aggregation"]
P4 --> P5["Page 5\nRecommendations"]
P5 --> P6["Page 6\nDecision Execution"]
```
## Components and Interfaces
### Terminology Map
The core of the sanitization is a defined mapping from financial/trading terms to domain-neutral equivalents. The map is applied consistently across all files.
#### System and Provider Names
| Source Term | Sanitized Replacement |
|-------------|----------------------|
| Stonks Oracle / stonks | the platform / the system |
| Polygon.io / Polygon | external data provider / data source API |
| SEC EDGAR / SEC / EFTS | public records API / regulatory filings source |
| Alpaca / AlpacaBrokerAdapter | execution adapter / external execution API |
| Wall Street | (removed or reframed) |
#### Trading and Financial Actions
| Source Term | Sanitized Replacement |
|-------------|----------------------|
| buy | act |
| sell | defer |
| hold | monitor |
| watch | observe |
| trading engine | decision execution engine |
| paper trading / paper_eligible | simulation mode / simulation_eligible |
| live trading / live_eligible | live execution mode / production_eligible |
| trade / trading (as action) | decision / execution |
| order (broker order) | execution request |
| pre-trade checks | pre-execution checks |
#### Financial Concepts
| Source Term | Sanitized Replacement |
|-------------|----------------------|
| portfolio | resource pool / allocation pool |
| portfolio allocation | resource allocation |
| portfolio heat | pool exposure |
| portfolio snapshots | pool snapshots |
| position sizing | commitment sizing / resource allocation |
| position (open position) | commitment / active commitment |
| stop-loss | risk threshold / loss limit |
| take-profit | gain target |
| bullish | positive / favorable |
| bearish | negative / unfavorable |
| stock ticker / ticker symbol | entity identifier |
| stock market | (removed or reframed) |
| earnings / earnings call / earnings report | performance report / periodic disclosure |
| 10-K / 10-Q / 8-K | regulatory filing types |
| SEC filings | regulatory filings |
| broker / broker API | execution adapter / execution API |
| P&L | gain/loss |
| Sharpe ratio | risk-adjusted return ratio |
| drawdown | peak-to-trough decline |
| win rate | success rate |
#### Ticker Symbols and Company Names
| Source Term | Sanitized Replacement |
|-------------|----------------------|
| AAPL / Apple | Entity-A |
| TSLA / Tesla | Entity-B |
| NVDA / NVIDIA | Entity-C |
| XOM | Entity-D |
| META | Entity-E |
| Any other ticker | Entity-{letter} or "tracked entity" |
#### Redis Keys
| Source Pattern | Sanitized Pattern |
|----------------|-------------------|
| `stonks:queue:*` | `app:queue:*` |
| `stonks:dedupe:*` | `app:dedupe:*` |
| `stonks:ratelimit:*` | `app:ratelimit:*` |
| `stonks:trading:circuit_breaker:*` | `app:execution:circuit_breaker:*` |
| `stonks:dedupe:trading:*` | `app:dedupe:execution:*` |
#### MinIO Buckets
| Source Bucket | Sanitized Bucket |
|---------------|-----------------|
| `stonks-raw-market` | `app-raw-data` |
| `stonks-raw-news` | `app-raw-content` |
| `stonks-raw-filings` | `app-raw-filings` |
| `stonks-normalized` | `app-normalized` |
| `stonks-llm-prompts` | `app-llm-prompts` |
| `stonks-llm-results` | `app-llm-results` |
#### Database Tables
| Source Table | Sanitized Table |
|-------------|----------------|
| `trading_decisions` | `execution_decisions` |
| `portfolio_snapshots` | `pool_snapshots` |
| `portfolio_pct` (column) | `allocation_pct` |
All other table names (`documents`, `document_intelligence`, `trend_windows`, `recommendations`, etc.) are already domain-neutral and remain unchanged.
#### Adapter and Source Type Names
| Source Term | Sanitized Replacement |
|-------------|----------------------|
| `PolygonNewsAdapter` | `ExternalNewsAdapter` |
| `PolygonMarketAdapter` | `ExternalDataAdapter` |
| `SECEdgarAdapter` | `RegulatoryFilingsAdapter` |
| `AlpacaBrokerAdapter` | `ExecutionAdapter` |
| `broker` (source_type) | `execution_api` |
| `market_api` (source_type) | `data_api` |
| `filings_api` (source_type) | `filings_api` (unchanged — already neutral) |
### Preserved Engineering Terms
The following terms are explicitly preserved because they describe engineering patterns, not financial concepts:
- **circuit breaker** — engineering safety pattern for rate limiting and cascading failure prevention
- **exponential backoff** — retry pattern
- **adapter pattern** — software design pattern (only the domain-specific adapter *names* are sanitized)
- **signal** — used in signal processing and scoring context
- **trend**, **sentiment**, **confidence**, **contradiction**, **evidence** — data analysis terms
- **recency decay**, **credibility weight**, **novelty bonus** — scoring algorithm terms
- **weighted sentiment average** — mathematical computation term
### Preserved Technical Content
All of the following are preserved verbatim (with only the terminology map applied to embedded financial terms):
- Composite signal scoring formula: `combined = gate × recency × credibility × (1 + novelty_bonus) × market_context_multiplier`
- Confidence computation formula with log₂ scaling and four components
- Weighted sentiment average formula
- All threshold values, configuration parameters, and numeric constants
- All Markdown table structures containing technical parameters
- All code module path references (e.g., `services/aggregation/scoring.py`)
- Three-layer signal architecture with weight ratios (1.0, 0.3, 0.2)
- Contradiction detection algorithm and evidence ranking methodology
- All PostgreSQL table structures and column descriptions (with sanitized names where needed)
- All Redis queue patterns and operations (`rpush`/`lpop`/`blpop`)
- All MinIO storage patterns (with sanitized bucket names)
- Ollama as the LLM inference provider
### Index Page Reframing
The sanitized `index.md` describes the system as an "AI-driven intelligence-to-decision pipeline" that:
1. Ingests data from multiple external data sources
2. Extracts structured intelligence via NLP/LLM
3. Scores and weights signals
4. Aggregates trends across time windows
5. Generates recommendations with quality gates
6. Executes decisions autonomously with safety mechanisms
References to "Stonks Oracle" are replaced with "the platform" or "the system". References to financial-specific APIs (Polygon.io, SEC EDGAR) are replaced with neutral descriptions. The "Related Documentation" section links are updated to use neutral descriptions or removed if they reference financial-specific content.
### Page 06 Reframing
Page 06 undergoes the most extensive reframing since it covers the trading engine. Key changes:
- Title: "Decision Execution" instead of "Trading Decisions and Execution"
- "Trading engine" → "decision execution engine"
- "Pre-trade checks" → "pre-execution checks"
- "Broker adapter" / "Alpaca" → "execution adapter" / "external execution API"
- "Paper trading" → "simulation mode"
- "Live trading" → "live execution mode"
- "Portfolio" → "resource pool" / "allocation pool"
- "Position" → "commitment" / "active commitment"
- "Stop-loss" → "risk threshold"
- "Take-profit" → "gain target"
- All order submission language reframed as "execution request submission"
### Diagram Sanitization
Each Mermaid diagram file receives the same terminology map treatment:
- Node labels containing financial terms are replaced
- Queue name labels (`stonks:queue:*``app:queue:*`)
- Bucket name labels (`stonks-raw-market``app-raw-data`)
- Table name labels (`trading_decisions``execution_decisions`)
- Adapter names in node labels
- Subgraph titles containing financial terms
- The `trading-engine-decision-loop.md` diagram is renamed to `decision-engine-loop.md`
Mermaid syntax, node relationships, subgraph structures, and flow directions are preserved exactly.
## Data Models
This feature produces only documentation files. There are no new data models, database tables, or schema changes.
The sanitized narrative pages reference the same data models as the originals, with terminology-mapped names where applicable:
- **`WeightedSignal`** — document reference + composite weight + sentiment + impact (unchanged)
- **`SignalWeight`** — breakdown of recency, credibility, novelty, confidence gate, market context multiplier (unchanged)
- **`TrendSummary`** — rolling trend for an entity across a time window (unchanged)
- **`Recommendation`** — actionable decision recommendation (reframed from "trade recommendation")
- **`execution_decisions`** table — audit record of every decision evaluation (sanitized from `trading_decisions`)
- **`pool_snapshots`** table — resource pool state snapshots (sanitized from `portfolio_snapshots`)
## Correctness Properties
*A property is a characteristic or behavior that should hold true across all valid executions of a system — essentially, a formal statement about what the system should do. Properties serve as the bridge between human-readable specifications and machine-verifiable correctness guarantees.*
The sanitized documentation set has one key universal property: the complete absence of financial/trading terminology across all output files. This is well-suited to property-based testing because the property must hold for *every* file in the output set, and the banned term list is large enough that systematic checking across all files provides high-value coverage.
### Property 1: Banned Financial Terminology Exclusion
*For any* file in the sanitized documentation set (`docs/sanitized-pipeline-deep-dive/`), the file content shall not contain any term from the comprehensive banned financial terminology list. The banned list includes: stock ticker symbols (AAPL, TSLA, NVDA, XOM, META, and all 50 tracked tickers), company names used as financial examples (Apple, Tesla, NVIDIA), trading action labels (buy, sell, hold, watch as action labels — BUY, SELL, HOLD, WATCH in uppercase), financial system terms (trading engine, paper trading, live trading, paper_eligible, live_eligible, portfolio, portfolio allocation, portfolio heat, portfolio snapshots, broker, Alpaca, broker adapter, broker API, stock market, Wall Street, bullish, bearish, position sizing, stop-loss), financial event terms (SEC EDGAR, SEC filings, 10-K, 10-Q, 8-K, earnings, earnings call, earnings report), provider names (Polygon.io, Polygon), system names (Stonks Oracle, stonks), and infrastructure patterns containing financial terms (stonks: prefix in Redis keys, stonks- prefix in MinIO buckets, trading_decisions table name, portfolio_snapshots table name).
**Validates: Requirements 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 3.10, 6.2, 7.1, 7.2, 7.3, 8.1, 8.2**
## Error Handling
Since this is a documentation-only deliverable, there is no runtime error handling to design. The primary quality concerns are:
### Accuracy of Terminology Replacement
Every financial/trading term must be replaced with its domain-neutral equivalent. Missing a single instance of "stonks" in a Redis key pattern or "AAPL" in an example scenario would violate the sanitization requirements. The terminology map defined in the Components section serves as the authoritative reference.
### Preservation of Technical Content
The sanitization must not accidentally remove or alter engineering content. Key risks:
- **Formula corruption**: The composite weight formula contains `market_context_multiplier` — the word "market" must not be blindly replaced since it's part of a technical variable name
- **Code path corruption**: Module paths like `services/trading/engine.py` contain "trading" — these paths reference actual files and must be preserved as-is (the code files are not being renamed)
- **Table name corruption**: Database table names like `trading_decisions` need sanitization in narrative text but the actual SQL/code references to the original table names should be handled carefully
**Design decision**: Code module paths (e.g., `services/trading/engine.py`) are preserved exactly as they appear in the source, since they reference actual files in the repository. Only narrative references to concepts (e.g., "the trading engine") are sanitized. Variable names within formulas and code blocks are preserved. Database table names are sanitized in narrative descriptions and table listings, but inline code references note the sanitized name.
### Cross-Reference Integrity
All internal links must resolve to files that exist in the sanitized output:
- Page-to-page links must use sanitized filenames
- Diagram links must use sanitized diagram filenames
- No links should point back to the source `docs/intelligence-pipeline-deep-dive/` directory
## Testing Strategy
### Why Limited PBT Applies
This is a documentation-only deliverable — the output is static Markdown files, not executable code with functions and data transformations. However, one universal property (banned term exclusion) is well-suited to property-based testing because it must hold across all files and involves checking a large set of terms against file content.
Most other requirements (structural checks, content preservation, narrative reframing) are better verified through example-based tests and manual review.
### Property-Based Tests
- **Library**: Hypothesis (Python, already in the project)
- **Configuration**: `@settings(max_examples=100)`
- **Property 1 implementation**: Generate random selections from the banned term list and random file selections from the sanitized docs, verify the term does not appear in the file content. Alternatively, exhaustively check all banned terms against all files (since the file set is small and fixed, this is more practical as an exhaustive example-based test).
**Practical note**: Given the small, fixed file set (14 files), the banned term exclusion property is most practically implemented as an exhaustive check — iterate all files × all banned terms — rather than a randomized property test. This provides complete coverage rather than probabilistic coverage.
### Example-Based Tests
1. **File structure verification**: Verify all expected files exist at the correct paths
2. **Cross-reference integrity**: Parse all sanitized files, extract markdown links, verify they resolve to existing sanitized files
3. **Mermaid syntax validation**: Verify each diagram file contains valid Mermaid `flowchart` declarations
4. **Technical content preservation**: Spot-check that key formulas, threshold values, and code module paths are present in the sanitized docs
5. **Terminology replacement verification**: Spot-check that key replacements appear (e.g., "decision execution engine" replaces "trading engine")
6. **Index page framing**: Verify the index describes the system as an "AI-driven intelligence-to-decision pipeline"
7. **Database table sanitization**: Verify `execution_decisions` appears where `trading_decisions` was, and `pool_snapshots` where `portfolio_snapshots` was
### Manual Review
- Narrative coherence and readability of the sanitized content
- Consistency of domain-neutral framing across all pages
- Quality of example scenario replacements (e.g., "bearish article about AAPL" → "negative-sentiment article about Entity-A")
- Preservation of page-to-page transition flow
@@ -0,0 +1,202 @@
# Requirements Document
## Introduction
This feature produces a sanitized version of the existing 6-page intelligence pipeline deep dive documentation (`docs/intelligence-pipeline-deep-dive/`) for use in a work presentation. The sanitized version strips all financial, market, and trading language — stock tickers, buy/sell/hold actions, portfolio allocation, broker APIs, and domain-specific framing — and reframes the content as a general-purpose AI decision intelligence pipeline. The sanitized docs are stored as a separate doc group under `docs/sanitized-pipeline-deep-dive/`, preserving the original documents untouched. All engineering depth — algorithms, formulas, architectural patterns, queue topologies, database schemas, code module references, and Mermaid diagrams — is preserved. Only the domain-specific framing changes.
## Glossary
- **Source_Docs**: The original 6-page documentation set at `docs/intelligence-pipeline-deep-dive/`, including `index.md`, pages `01` through `06`, and the `diagrams/` subdirectory containing 6 Mermaid diagram files.
- **Sanitized_Docs**: The output documentation set at `docs/sanitized-pipeline-deep-dive/`, mirroring the structure of Source_Docs with all financial/market/trading language replaced by domain-neutral equivalents.
- **Sanitization_Engine**: The process (manual or automated) that transforms Source_Docs into Sanitized_Docs by applying the terminology mapping and content reframing rules defined in this document.
- **Terminology_Map**: The defined set of financial/market/trading terms and their domain-neutral replacements used by the Sanitization_Engine.
- **Entity_Identifier**: The domain-neutral replacement for stock ticker symbols (e.g., AAPL, TSLA) in Sanitized_Docs.
- **Decision_Term**: A domain-neutral action term (act, defer, monitor, observe) that replaces trading actions (buy, sell, hold, watch) in Sanitized_Docs.
- **Decision_Execution_Engine**: The domain-neutral name for the trading engine in Sanitized_Docs.
- **Execution_Adapter**: The domain-neutral name for broker adapters and broker API references in Sanitized_Docs.
- **Allocation_Pool**: The domain-neutral name for portfolio references in Sanitized_Docs.
- **Commitment_Sizing**: The domain-neutral name for position sizing in Sanitized_Docs.
---
## Requirements
### Requirement 1: Separate Output Directory
**User Story:** As a presenter, I want the sanitized docs stored in a separate directory from the originals, so that the original documentation remains untouched and both versions coexist.
#### Acceptance Criteria
1. THE Sanitization_Engine SHALL write all output files to `docs/sanitized-pipeline-deep-dive/`.
2. THE Sanitization_Engine SHALL NOT modify, overwrite, or delete any file under `docs/intelligence-pipeline-deep-dive/`.
3. THE Sanitized_Docs SHALL contain an `index.md` file at the root of `docs/sanitized-pipeline-deep-dive/`.
4. THE Sanitized_Docs SHALL contain a `diagrams/` subdirectory under `docs/sanitized-pipeline-deep-dive/`.
---
### Requirement 2: Mirror the 6-Page Structure
**User Story:** As a presenter, I want the sanitized docs to mirror the same 6-page structure as the originals, so that readers familiar with the original can navigate the sanitized version identically.
#### Acceptance Criteria
1. THE Sanitized_Docs SHALL contain exactly 6 numbered page files matching the naming pattern of Source_Docs: `01-*.md` through `06-*.md`.
2. THE Sanitized_Docs SHALL contain an `index.md` with a table of contents linking to all 6 pages and all diagrams, mirroring the structure of the Source_Docs index.
3. THE Sanitized_Docs SHALL contain one Mermaid diagram file in `diagrams/` for each diagram file present in `docs/intelligence-pipeline-deep-dive/diagrams/`.
4. WHEN a Source_Docs page contains internal cross-references to other pages or diagrams, THE Sanitized_Docs equivalent page SHALL contain corresponding cross-references pointing to the Sanitized_Docs versions of those pages and diagrams.
5. THE Sanitized_Docs page filenames SHALL use sanitized titles (e.g., `06-decision-execution.md` instead of `06-trading-decisions-and-execution.md`).
---
### Requirement 3: Strip Financial and Trading Terminology
**User Story:** As a presenter, I want all financial, market, and trading language removed from the sanitized docs, so that the presentation focuses on engineering without revealing the financial domain.
#### Acceptance Criteria
1. THE Sanitized_Docs SHALL NOT contain any stock ticker symbols (e.g., AAPL, TSLA, NVDA, XOM, META).
2. THE Sanitized_Docs SHALL NOT contain the trading action terms "buy", "sell", "hold", or "watch" when used as system action labels or decision outputs.
3. THE Sanitized_Docs SHALL NOT contain the terms "trading engine", "paper trading", "live trading", "paper_eligible", or "live_eligible".
4. THE Sanitized_Docs SHALL NOT contain the terms "portfolio", "portfolio allocation", "portfolio heat", or "portfolio snapshots" when referring to the resource management domain concept.
5. THE Sanitized_Docs SHALL NOT contain references to "broker", "Alpaca", "broker adapter", or "broker API".
6. THE Sanitized_Docs SHALL NOT contain the terms "stock market", "Wall Street", "bullish", "bearish", "position sizing" (as a financial concept label), or "stop-loss" (as a financial concept label).
7. THE Sanitized_Docs SHALL NOT contain company names used as financial examples (e.g., "Apple", "Tesla", "NVIDIA" when used in a stock/market context).
8. THE Sanitized_Docs SHALL NOT contain the terms "SEC EDGAR", "SEC filings", "10-K", "10-Q", "8-K", "earnings", "earnings call", or "earnings report" as domain-specific financial references.
9. THE Sanitized_Docs SHALL NOT contain references to "Polygon.io" or "Polygon" as a financial data provider name.
10. THE Sanitized_Docs SHALL NOT contain the term "Stonks Oracle" or "stonks" as a system name.
---
### Requirement 4: Apply Domain-Neutral Terminology Mapping
**User Story:** As a presenter, I want consistent domain-neutral replacements for all stripped terms, so that the sanitized docs read coherently as a general-purpose AI decision intelligence pipeline.
#### Acceptance Criteria
1. WHEN the Source_Docs use "stock ticker" or specific ticker symbols, THE Sanitized_Docs SHALL use "entity identifier" or "tracked entity".
2. WHEN the Source_Docs use "buy/sell/hold/watch" as action labels, THE Sanitized_Docs SHALL use "act/defer/monitor/observe" or equivalent neutral decision terms.
3. WHEN the Source_Docs use "trading engine", THE Sanitized_Docs SHALL use "decision execution engine" or "action engine".
4. WHEN the Source_Docs use "portfolio", THE Sanitized_Docs SHALL use "resource pool" or "allocation pool".
5. WHEN the Source_Docs use "broker" or "Alpaca", THE Sanitized_Docs SHALL use "execution adapter" or "external execution API".
6. WHEN the Source_Docs use "paper trading", THE Sanitized_Docs SHALL use "simulation mode" or "dry-run mode".
7. WHEN the Source_Docs use "live trading", THE Sanitized_Docs SHALL use "live execution mode" or "production mode".
8. WHEN the Source_Docs use "bullish" or "bearish", THE Sanitized_Docs SHALL use "positive" or "negative" (or "favorable"/"unfavorable").
9. WHEN the Source_Docs use "position sizing", THE Sanitized_Docs SHALL use "resource allocation" or "commitment sizing".
10. WHEN the Source_Docs use "stop-loss", THE Sanitized_Docs SHALL use "risk threshold" or "loss limit".
11. WHEN the Source_Docs use "Stonks Oracle" or "stonks", THE Sanitized_Docs SHALL use a neutral system name such as "the platform" or "the system".
12. WHEN the Source_Docs use "SEC EDGAR" or "SEC filings", THE Sanitized_Docs SHALL use "regulatory filings source" or "public records API".
13. WHEN the Source_Docs use "Polygon.io" or "Polygon", THE Sanitized_Docs SHALL use "external data provider" or "data source API".
14. WHEN the Source_Docs use "earnings" as a catalyst type or event, THE Sanitized_Docs SHALL use "performance report" or "periodic disclosure".
15. THE Sanitized_Docs SHALL apply the Terminology_Map consistently across all 6 pages, the index, and all diagram files.
---
### Requirement 5: Preserve Engineering and Technical Depth
**User Story:** As a presenter, I want all engineering concepts, algorithms, formulas, and architectural details preserved, so that the sanitized docs demonstrate the technical sophistication of the system.
#### Acceptance Criteria
1. THE Sanitized_Docs SHALL preserve all references to Redis queue patterns, including queue names and `rpush`/`lpop`/`blpop` operations.
2. THE Sanitized_Docs SHALL preserve all references to PostgreSQL tables, including table names and column descriptions.
3. THE Sanitized_Docs SHALL preserve all references to MinIO buckets and storage patterns.
4. THE Sanitized_Docs SHALL preserve all references to Ollama as the LLM inference provider.
5. THE Sanitized_Docs SHALL preserve the composite signal scoring formula: `combined = gate × recency × credibility × (1 + novelty_bonus) × market_context_multiplier`.
6. THE Sanitized_Docs SHALL preserve the confidence computation formula with log₂ scaling and its four components (unique source count, average extraction credibility, signal agreement with sample-size dampening, contradiction penalty).
7. THE Sanitized_Docs SHALL preserve the weighted sentiment average formula: `weighted_avg = Σ(combined_weight × impact_score × sentiment_value) / Σ(combined_weight × impact_score)`.
8. THE Sanitized_Docs SHALL preserve all code module path references (e.g., `services/aggregation/scoring.py`, `services/recommendation/eligibility.py`).
9. THE Sanitized_Docs SHALL preserve the three-layer signal architecture, renaming the layers with domain-neutral labels (e.g., "Entity-Specific Signals", "Environmental Signals", "Relational Signals") while retaining the weight ratios (1.0, 0.3, 0.2).
10. THE Sanitized_Docs SHALL preserve all threshold values, configuration parameters, and numeric constants (e.g., confidence gate of 0.2, recency half-lives per window, eligibility thresholds).
11. THE Sanitized_Docs SHALL preserve all Markdown table structures containing technical parameters and thresholds.
12. THE Sanitized_Docs SHALL preserve the contradiction detection algorithm, evidence ranking methodology, and trend projection computation.
---
### Requirement 6: Sanitize Mermaid Diagrams
**User Story:** As a presenter, I want the Mermaid diagrams sanitized with the same terminology mapping as the narrative pages, so that diagrams and text are consistent.
#### Acceptance Criteria
1. THE Sanitized_Docs SHALL contain one sanitized Mermaid diagram file for each of the 6 diagram files in Source_Docs.
2. WHEN a Source_Docs diagram contains financial/trading terminology (e.g., "trading engine", "buy/sell", "paper_eligible", "bullish/bearish", ticker symbols), THE corresponding Sanitized_Docs diagram SHALL use the same domain-neutral replacements defined in the Terminology_Map.
3. THE Sanitized_Docs diagrams SHALL preserve all Mermaid syntax, node relationships, subgraph structures, and flow directions from the Source_Docs diagrams.
4. THE Sanitized_Docs diagrams SHALL preserve all code module path references and service names within diagram nodes.
5. THE Sanitized_Docs diagram filenames SHALL use sanitized names where the original names contain financial terms (e.g., `decision-engine-loop.md` instead of `trading-engine-decision-loop.md`).
---
### Requirement 7: Sanitize Redis Key and Queue Name References
**User Story:** As a presenter, I want Redis key patterns and queue names sanitized where they contain financial terms, so that even infrastructure-level references are domain-neutral.
#### Acceptance Criteria
1. WHEN a Source_Docs Redis queue name contains "stonks" (e.g., `stonks:queue:ingestion`), THE Sanitized_Docs SHALL replace "stonks" with a neutral prefix (e.g., `app:queue:ingestion`).
2. WHEN a Source_Docs Redis key pattern contains "trading" (e.g., `stonks:queue:broker_orders`, `stonks:trading:circuit_breaker:*`), THE Sanitized_Docs SHALL replace the trading-specific segment with a neutral equivalent (e.g., `app:queue:execution_orders`, `app:execution:circuit_breaker:*`).
3. THE Sanitized_Docs SHALL apply Redis key sanitization consistently across all narrative pages and diagram files.
---
### Requirement 8: Sanitize MinIO Bucket Name References
**User Story:** As a presenter, I want MinIO bucket names sanitized where they contain financial terms, so that storage references are domain-neutral.
#### Acceptance Criteria
1. WHEN a Source_Docs MinIO bucket name contains "stonks" (e.g., `stonks-raw-market`, `stonks-raw-news`, `stonks-normalized`), THE Sanitized_Docs SHALL replace "stonks" with a neutral prefix (e.g., `app-raw-data`, `app-raw-content`, `app-normalized`).
2. THE Sanitized_Docs SHALL apply MinIO bucket name sanitization consistently across all narrative pages and diagram files.
---
### Requirement 9: Sanitize Database Table and Column References Where Needed
**User Story:** As a presenter, I want database table and column names that contain obvious financial terms sanitized, while preserving the overall schema structure.
#### Acceptance Criteria
1. WHEN a Source_Docs database table name contains "trading" (e.g., `trading_decisions`), THE Sanitized_Docs SHALL use a neutral equivalent (e.g., `execution_decisions`).
2. WHEN a Source_Docs database table or column references "portfolio" (e.g., `portfolio_snapshots`, `portfolio_pct`), THE Sanitized_Docs SHALL use a neutral equivalent (e.g., `pool_snapshots`, `allocation_pct`).
3. THE Sanitized_Docs SHALL preserve all other database table names that do not contain financial-specific terms (e.g., `documents`, `document_intelligence`, `trend_windows`, `recommendations`).
4. THE Sanitized_Docs SHALL apply database reference sanitization consistently across all narrative pages.
---
### Requirement 10: Sanitize Example Scenarios and Inline References
**User Story:** As a presenter, I want all inline examples, scenario walkthroughs, and narrative references sanitized, so that no financial context leaks through illustrative content.
#### Acceptance Criteria
1. WHEN a Source_Docs page uses a specific company name or ticker in an example scenario (e.g., "a bearish article about AAPL"), THE Sanitized_Docs SHALL replace the reference with a generic entity (e.g., "a negative-sentiment article about Entity-A").
2. WHEN a Source_Docs page describes a financial event as an example (e.g., "earnings miss", "tariff announcement affecting XOM"), THE Sanitized_Docs SHALL reframe the example using domain-neutral language (e.g., "a negative performance disclosure", "a regulatory policy change affecting Entity-B").
3. WHEN a Source_Docs page references market-specific concepts in narrative flow (e.g., "markets move fast", "trading volume", "intraday swings"), THE Sanitized_Docs SHALL reframe using neutral language (e.g., "conditions change rapidly", "activity volume", "short-term fluctuations").
4. THE Sanitized_Docs SHALL preserve the logical structure and teaching purpose of all example scenarios while removing the financial framing.
---
### Requirement 11: Preserve Acceptable Engineering Terms
**User Story:** As a presenter, I want general engineering terms that happen to overlap with financial language preserved when they describe engineering patterns, so that the technical accuracy is maintained.
#### Acceptance Criteria
1. THE Sanitized_Docs SHALL preserve the term "circuit breaker" when it describes the engineering safety pattern (rate limiting, cascading failure prevention).
2. THE Sanitized_Docs SHALL preserve the term "exponential backoff" and all retry/backoff patterns.
3. THE Sanitized_Docs SHALL preserve all adapter pattern references (the software design pattern), renaming only the domain-specific adapter names (e.g., "AlpacaBrokerAdapter" becomes a neutral name).
4. THE Sanitized_Docs SHALL preserve the term "signal" as used in the signal processing and scoring context.
5. THE Sanitized_Docs SHALL preserve the terms "trend", "sentiment", "confidence", "contradiction", and "evidence" as used in the data analysis context.
---
### Requirement 12: Reframe the System Narrative
**User Story:** As a presenter, I want the overall system narrative reframed as a general-purpose AI decision intelligence pipeline, so that the presentation tells a coherent story without financial context.
#### Acceptance Criteria
1. THE Sanitized_Docs index page SHALL describe the system as an "AI-driven intelligence-to-decision pipeline" that ingests data from multiple sources, extracts structured intelligence via NLP/LLM, scores and weights signals, aggregates trends across time windows, generates recommendations with quality gates, and executes decisions autonomously with safety mechanisms.
2. THE Sanitized_Docs page 01 SHALL describe data ingestion from "multiple external data sources" rather than from financial-specific APIs.
3. THE Sanitized_Docs page 06 SHALL describe "autonomous decision execution with safety mechanisms" rather than "trading decisions and execution".
4. WHEN the Source_Docs conclusion references the "intelligence-to-decision pipeline in Stonks Oracle", THE Sanitized_Docs conclusion SHALL reference the "intelligence-to-decision pipeline" without a financial system name.
5. THE Sanitized_Docs SHALL maintain the narrative flow where each page ends with a transition to the next page, preserving the end-to-end story structure.
@@ -0,0 +1,47 @@
# Tasks — Sanitized Pipeline Documentation
## Task 1: Create Output Directory and Index Page
- [x] 1.1 Create the `docs/sanitized-pipeline-deep-dive/` directory and `diagrams/` subdirectory
- [x] 1.2 Create `docs/sanitized-pipeline-deep-dive/index.md` with sanitized content: replace "Stonks Oracle" with "the platform", replace Polygon.io/SEC EDGAR references with neutral descriptions, update all page links to use sanitized filenames (e.g., `06-decision-execution.md`), update diagram links to use sanitized names (e.g., `decision-engine-loop.md`), describe the system as an "AI-driven intelligence-to-decision pipeline", and update or remove the Related Documentation section to use neutral descriptions
## Task 2: Sanitize Page 01 — Data Ingestion and Preparation
- [x] 2.1 Create `docs/sanitized-pipeline-deep-dive/01-data-ingestion-and-preparation.md` by transforming the source page: replace "Stonks Oracle" with "the platform", replace "Polygon.io" with "external data provider", replace "SEC EDGAR"/"EFTS" with "public records API"/"regulatory filings source", replace "AlpacaBrokerAdapter" with "ExecutionAdapter", replace adapter class names (PolygonNewsAdapter → ExternalNewsAdapter, PolygonMarketAdapter → ExternalDataAdapter, SECEdgarAdapter → RegulatoryFilingsAdapter), replace all `stonks:` Redis key prefixes with `app:`, replace MinIO bucket names (stonks-raw-market → app-raw-data, stonks-raw-news → app-raw-content, stonks-raw-filings → app-raw-filings, stonks-normalized → app-normalized), replace ticker symbols (AAPL → Entity-A, etc.) and company names with generic entities, replace "broker" source_type with "execution_api", replace "SEC" references with "regulatory filings", replace "10-K"/"10-Q"/"8-K" with "regulatory filing types", replace "earnings" with "performance report", sanitize example paths (e.g., `news_api/AAPL/...``news_api/Entity-A/...`), update cross-references to use sanitized filenames, and preserve all engineering content (queue operations, table structures, quality scoring formula, code module paths)
## Task 3: Sanitize Page 02 — AI Agent Processing and Extraction
- [x] 3.1 Create `docs/sanitized-pipeline-deep-dive/02-ai-agent-processing-and-extraction.md` by transforming the source page: replace "Stonks Oracle" references, replace financial document type references (SEC filings → regulatory filings, earnings transcripts → performance transcripts), replace "financial document analyst" role description with "document analyst", replace ticker symbols and company names in examples (AAPL, TSLA, NVDA, XOM, META → Entity-A through Entity-E), replace "bearish"/"bullish" with "negative"/"positive", replace "earnings" catalyst type references with "performance_report", replace "stock ticker" with "entity identifier", replace "market implications" with neutral language, replace `stonks:queue:*` Redis keys with `app:queue:*`, replace MinIO bucket names (stonks-llm-prompts → app-llm-prompts, stonks-llm-results → app-llm-results, stonks-normalized → app-normalized), replace "tariff announcement affecting XOM" example with neutral equivalent, update cross-references, and preserve all engineering content (JSON repair pipeline, validation logic, AgentConfigResolver, Ollama references, code module paths, schema field descriptions)
## Task 4: Sanitize Page 03 — Signal Scoring and Weighted Signals
- [x] 4.1 Create `docs/sanitized-pipeline-deep-dive/03-signal-scoring-and-weighted-signals.md` by transforming the source page: replace "bullish"/"bearish" with "positive"/"negative" throughout, replace "trading recommendations" with "decision recommendations", replace ticker examples (AAPL, NVDA) with Entity-A/Entity-C, replace "market context" variable references carefully (preserve `market_context_multiplier` as a technical variable name but sanitize narrative references to "market conditions" → "environmental conditions"), replace "trading volume" with "activity volume", replace `stonks:queue:*` Redis keys with `app:queue:*`, replace "bullish_pct > bearish_pct" with "positive_pct > negative_pct" in signal propagation description, update cross-references, and preserve all engineering content (composite weight formula, recency decay formula, half-life tables, credibility weight computation, novelty bonus formula, weighted sentiment average formula, three-layer architecture with weight ratios 1.0/0.3/0.2, all threshold values and configuration parameters)
## Task 5: Sanitize Page 04 — Trend Aggregation and Accumulating Signals
- [x] 5.1 Create `docs/sanitized-pipeline-deep-dive/04-trend-aggregation-and-accumulating-signals.md` by transforming the source page: replace "bullish"/"bearish" with "positive"/"negative" in trend direction descriptions and TrendDirection enum values, replace "trading recommendations" with "decision recommendations", replace "BULLISH_THRESHOLD"/"BEARISH_THRESHOLD" with "POSITIVE_THRESHOLD"/"NEGATIVE_THRESHOLD", replace "paper_eligible"/"live_eligible" with "simulation_eligible"/"production_eligible", replace "paper trading"/"live trading" with "simulation mode"/"live execution mode", replace "buy"/"sell"/"hold"/"watch" action labels with "act"/"defer"/"monitor"/"observe", replace "trading_decisions" table with "execution_decisions", replace "portfolio" references, replace ticker examples (AAPL) with Entity-A, replace "earnings miss" example with "negative performance disclosure", replace `stonks:queue:*` Redis keys with `app:queue:*`, update cross-references, and preserve all engineering content (five time windows, trend direction derivation thresholds, contradiction detection algorithm, evidence ranking, confidence computation formula with log₂ scaling, trend projection computation, all persistence tables)
## Task 6: Sanitize Page 05 — Recommendation Generation
- [x] 6.1 Create `docs/sanitized-pipeline-deep-dive/05-recommendation-generation.md` by transforming the source page: replace "buy"/"sell"/"hold"/"watch" action labels with "act"/"defer"/"monitor"/"observe", replace "BUY"/"SELL"/"HOLD"/"WATCH" with "ACT"/"DEFER"/"MONITOR"/"OBSERVE", replace "paper_eligible"/"live_eligible" with "simulation_eligible"/"production_eligible", replace "paper trading"/"live trading" with "simulation mode"/"live execution mode", replace "trading engine" with "decision execution engine", replace "portfolio" with "resource pool"/"allocation pool", replace "portfolio_pct" with "allocation_pct", replace "position sizing" with "commitment sizing", replace "position" (as financial position) with "commitment", replace "stop-loss" with "risk threshold", replace "trading-eligible" with "execution-eligible", replace "trade" (as noun/verb) with "decision"/"execution", replace ticker examples (AAPL) with Entity-A, replace "earnings" catalyst references with "performance_report", replace `stonks:queue:*` Redis keys with `app:queue:*`, replace "broker adapter" with "execution adapter", replace "Alpaca" with "external execution API", update cross-references to use sanitized filenames (06-decision-execution.md), and preserve all engineering content (suppression thresholds, eligibility gates, position sizing formulas, thesis generation logic, risk classification computation, all persistence tables)
## Task 7: Sanitize Page 06 — Decision Execution
- [x] 7.1 Create `docs/sanitized-pipeline-deep-dive/06-decision-execution.md` by transforming the source page: change title to "Decision Execution", replace "trading engine" with "decision execution engine" throughout, replace "TradingEngine" class references with "DecisionEngine" in narrative (preserve code module path `services/trading/engine.py`), replace "trade"/"trading" with "decision"/"execution" in narrative, replace "pre-trade checks" with "pre-execution checks", replace "buy"/"sell" action labels with "act"/"defer", replace "paper trading"/"paper_eligible" with "simulation mode"/"simulation_eligible", replace "live trading"/"live_eligible" with "live execution mode"/"production_eligible", replace "broker"/"Alpaca" with "execution adapter"/"external execution API", replace "AlpacaBrokerAdapter" with "ExecutionAdapter" in narrative, replace "portfolio" with "resource pool"/"allocation pool", replace "portfolio heat" with "pool exposure", replace "portfolio_snapshots" with "pool_snapshots", replace "position"/"positions" (financial) with "commitment"/"commitments", replace "position sizing"/"PositionSizer" with "commitment sizing" in narrative, replace "stop-loss" with "risk threshold", replace "take-profit" with "gain target", replace "P&L" with "gain/loss", replace "Sharpe ratio" with "risk-adjusted return ratio", replace "win rate" with "success rate", replace "drawdown" with "peak-to-trough decline", replace "trading_decisions" table with "execution_decisions", replace `stonks:queue:broker_orders` with `app:queue:execution_orders`, replace `stonks:trading:circuit_breaker:*` with `app:execution:circuit_breaker:*`, replace `stonks:dedupe:trading:*` with `app:dedupe:execution:*`, replace all other `stonks:` Redis key prefixes with `app:`, replace "paper-api.alpaca.markets" with "execution-api.example.com", replace "Polygon API" with "data source API", replace ticker examples with Entity-{letter}, replace "earnings" references with "performance report"/"periodic disclosure", update cross-references to use sanitized filenames, update the Conclusion section to remove "Stonks Oracle" and financial framing, and preserve all engineering content (5 concurrent async tasks, circuit breaker algorithm, reserve pool logic, risk tier parameters table, position sizing pipeline, order submission flow, all code module paths, all threshold values)
## Task 8: Sanitize Mermaid Diagrams
- [x] 8.1 Create `docs/sanitized-pipeline-deep-dive/diagrams/ingestion-to-extraction-flow.md` by transforming the source diagram: replace `stonks:queue:*` with `app:queue:*`, replace MinIO bucket names (stonks-raw-market → app-raw-data, stonks-raw-news → app-raw-content, stonks-raw-filings → app-raw-filings, stonks-normalized → app-normalized), replace adapter names in node labels (PolygonMarketAdapter → ExternalDataAdapter, PolygonNewsAdapter → ExternalNewsAdapter, SECEdgarAdapter → RegulatoryFilingsAdapter, MacroNewsAdapter unchanged, WebScrapeAdapter unchanged), replace "AlpacaBrokerAdapter" if present, and preserve all Mermaid syntax, node relationships, subgraph structures, flow directions, and code module paths
- [x] 8.2 Create `docs/sanitized-pipeline-deep-dive/diagrams/three-layer-signal-merging.md` by transforming the source diagram: replace `stonks:queue:*` with `app:queue:*`, replace "bullish_pct > bearish_pct" if present, and preserve all Mermaid syntax and structure
- [x] 8.3 Create `docs/sanitized-pipeline-deep-dive/diagrams/weighted-signal-computation.md` by copying the source diagram with minimal changes (content is already domain-neutral — only replace any `stonks:` references if present), preserving all Mermaid syntax and structure
- [x] 8.4 Create `docs/sanitized-pipeline-deep-dive/diagrams/trend-accumulation-escalation.md` by transforming the source diagram: replace "BULLISH"/"BEARISH" with "POSITIVE"/"NEGATIVE", replace "BUY / SELL" with "ACT / DEFER", replace "paper_eligible"/"live_eligible" if present, and preserve all Mermaid syntax and structure
- [x] 8.5 Create `docs/sanitized-pipeline-deep-dive/diagrams/recommendation-generation-flow.md` by transforming the source diagram: replace `stonks:queue:*` with `app:queue:*`, replace "BUY"/"SELL"/"HOLD"/"WATCH" with "ACT"/"DEFER"/"MONITOR"/"OBSERVE", replace "paper_eligible"/"live_eligible" with "simulation_eligible"/"production_eligible", replace "portfolio" with "allocation pool", and preserve all Mermaid syntax and structure
- [x] 8.6 Create `docs/sanitized-pipeline-deep-dive/diagrams/decision-engine-loop.md` (renamed from trading-engine-decision-loop.md) by transforming the source diagram: replace "Trading Engine" with "Decision Execution Engine", replace `stonks:queue:broker_orders` with `app:queue:execution_orders`, replace `stonks:dedupe:trading:*` with `app:dedupe:execution:*`, replace `stonks:trading:circuit_breaker:*` with `app:execution:circuit_breaker:*`, replace "buy, sell" with "act, defer", replace "paper_eligible, live_eligible" with "simulation_eligible, production_eligible", replace "Alpaca paper trading" with "external execution API (simulation)", replace "portfolio" references with "resource pool"/"allocation pool", replace "Portfolio heat" with "Pool exposure", replace "portfolio_snapshots" with "pool_snapshots", replace "trading_decisions" with "execution_decisions", replace "Sharpe ratio" with "risk-adjusted return ratio", replace "drawdown" with "peak-to-trough decline", replace "win rate" with "success rate", replace "P&L" with "gain/loss", and preserve all Mermaid syntax, node relationships, subgraph structures, flow directions, and code module paths
## Task 9: Verification and Cross-Reference Integrity
- [x] 9.1 Verify all sanitized files exist at the expected paths: index.md, 6 numbered pages (01-06), and 6 diagram files in diagrams/
- [x] 9.2 Verify no sanitized file contains any banned financial term: scan all files for ticker symbols (AAPL, TSLA, NVDA, XOM, META), company names (Apple, Tesla, NVIDIA as financial references), system names (Stonks Oracle, stonks), provider names (Polygon.io, Polygon, SEC EDGAR, Alpaca), financial terms (trading engine, paper trading, live trading, paper_eligible, live_eligible, portfolio, broker, bullish, bearish, position sizing, stop-loss, stock market, Wall Street, earnings, 10-K, 10-Q, 8-K), and infrastructure patterns (stonks: prefix, stonks- prefix, trading_decisions, portfolio_snapshots)
- [x] 9.3 Verify all internal cross-references resolve: parse all markdown links in sanitized files, confirm each link target exists in the sanitized output directory
- [x] 9.4 Verify key engineering content is preserved: check that the composite weight formula, confidence computation formula, weighted sentiment average formula, three-layer weight ratios (1.0, 0.3, 0.2), and key threshold values (confidence gate 0.2, eligibility confidence 0.35) appear in the sanitized docs
- [x] 9.5 Verify source files are unmodified: confirm that no files under `docs/intelligence-pipeline-deep-dive/` were changed
@@ -0,0 +1 @@
{"specId": "b595d834-7e72-4fab-87a9-65c92115a069", "workflowType": "requirements-first", "specType": "feature"}
+732
View File
@@ -0,0 +1,732 @@
# Design Document — Signal Math Upgrade
## Overview
This design upgrades the Stonks Oracle signal processing pipeline from deterministic heuristic formulas to a probabilistic, regime-aware, and adaptive mathematical framework. The upgrade spans all pipeline stages — signal scoring, trend assembly, macro impact, competitive signals, trend projection, and recommendation generation — while preserving the existing `WeightedSignal` abstraction, three-layer architecture, database schema, and dataclass interfaces.
The core transformation replaces:
- **Binary confidence gate** → smooth sigmoid transition
- **Weighted sentiment average** → Bayesian log-likelihood accumulation with Beta posterior
- **Fixed recency decay** → adaptive event-specific half-lives
- **Linear macro exposure** → multiplicative compounding exposure
- **Additive macro integration** → conditional multiplicative modifiers
- **Simple contradiction ratio** → weighted disagreement entropy
- **Heuristic trend confidence** → Bayesian posterior variance
- **Threshold-based direction** → entropy-based mixed signal detection
- **Simple momentum** → exponentially weighted momentum with volatility scaling
- **Confidence/strength gates** → expected value recommendation gate
- **Fixed relationship transfer** → graph-distance attenuated competitive signals
All changes are gated behind a `probabilistic_scoring_enabled` feature flag in `risk_configs`, allowing incremental rollout with instant rollback. New outputs (P_bull, α, β, entropy, regime, EV) are stored in existing JSONB columns — no database migrations required.
### Design Rationale
Markets are fundamentally probabilistic and regime-dependent. The current pipeline collapses rich evidence into binary sentiment labels and fixed-weight averages, losing uncertainty structure. A Bayesian framework preserves the full posterior distribution, enabling the system to distinguish between "strongly bullish" and "weakly bullish with high uncertainty" — a distinction that directly impacts position sizing and risk management.
The regime detector adapts scoring thresholds to market conditions (panic vs. trending vs. mean-reverting), and the expected value gate ensures recommendations only proceed when the risk-adjusted outcome is positive. Together, these changes transform the pipeline from a sentiment aggregator into a probabilistic forecasting engine.
---
## Architecture
### High-Level Pipeline Flow
The upgraded pipeline maintains the existing three-layer architecture but introduces new computation stages within each layer. The feature flag controls which computation path is taken at each stage.
```mermaid
flowchart TD
subgraph "Layer 1: Company Signals"
A[Document Intelligence Records] --> B[Signal Scorer]
B --> |"probabilistic=false"| C1[Binary Gate + Fixed Decay]
B --> |"probabilistic=true"| C2[Sigmoid Gate + Adaptive Decay<br/>+ Info Gain + Source Accuracy]
C1 --> D[WeightedSignal list]
C2 --> D
end
subgraph "Layer 2: Macro Signals"
E[Global Events] --> F[Macro Scorer]
F --> |"probabilistic=false"| G1[Linear Weighted Sum]
F --> |"probabilistic=true"| G2[Multiplicative Exposure]
G1 --> H[Macro WeightedSignals]
G2 --> H
end
subgraph "Layer 3: Competitive Signals"
I[Pattern Matcher] --> J[Signal Propagation]
J --> |"probabilistic=false"| K1[Flat Transfer Strength]
J --> |"probabilistic=true"| K2[Graph-Distance Attenuation]
K1 --> L[Competitive WeightedSignals]
K2 --> L
end
subgraph "Regime Detection (new)"
M[Market Data] --> N[Regime Detector]
N --> O{Regime Classification}
O --> P[trend-following / panic / mean-reversion / uncertainty]
end
subgraph "Trend Assembly"
D --> Q[Merge Signals]
H --> |"probabilistic=false"| Q
H --> |"probabilistic=true"| R[Conditional Macro Modifier]
R --> Q
L --> Q
Q --> S[Trend Assembler]
S --> |"probabilistic=false"| T1[Heuristic Confidence + Threshold Direction]
S --> |"probabilistic=true"| T2[Bayesian Posterior + Entropy Direction<br/>+ Regime-Adjusted Thresholds]
P --> T2
T1 --> U[TrendSummary]
T2 --> U
end
subgraph "Projection"
U --> V[Projection Engine]
V --> |"probabilistic=false"| W1[Simple Momentum]
V --> |"probabilistic=true"| W2[EW Momentum + Vol Scaling]
W1 --> X[TrendProjection]
W2 --> X
end
subgraph "Recommendation"
U --> Y[Recommendation Engine]
X --> Y
Y --> |"probabilistic=false"| Z1[Confidence + Strength Gates]
Y --> |"probabilistic=true"| Z2[EV Gate + Existing Gates]
Z1 --> AA[Recommendation]
Z2 --> AA
end
```
### Feature Flag Control Flow
The feature flag `probabilistic_scoring_enabled` is read from the `risk_configs` table's `config` JSONB column at the start of each aggregation cycle. It propagates through all pipeline stages via the existing `AggregationConfig` dataclass.
```mermaid
sequenceDiagram
participant W as Worker (aggregate_company)
participant DB as PostgreSQL (risk_configs)
participant S as Signal Scorer
participant T as Trend Assembler
participant R as Recommendation Engine
W->>DB: SELECT config FROM risk_configs WHERE active=TRUE
DB-->>W: {"macro_enabled": true, "competitive_enabled": true, "probabilistic_scoring_enabled": false}
W->>W: Log pipeline mode (heuristic or probabilistic)
W->>S: compute_signal_weight(..., probabilistic=flag)
S-->>W: WeightedSignal (with or without Bayesian fields)
W->>T: assemble_trend_summary(..., probabilistic=flag)
T-->>W: TrendSummary (with or without entropy/regime)
W->>R: evaluate_eligibility(..., probabilistic=flag)
R-->>W: Recommendation (with or without EV gate)
```
---
## Components and Interfaces
### New Modules
| Module | File | Responsibility |
|--------|------|----------------|
| Bayesian Accumulator | `services/aggregation/bayesian.py` | Log-likelihood accumulation, Beta posterior, P_bull, Bayesian confidence |
| Regime Detector | `services/aggregation/regime.py` | EMA computation, volatility ratio, regime classification, threshold adjustment |
| Adaptive Decay | integrated into `scoring.py` | Event-specific half-life computation from impact, surprise, market reaction |
| Information Gain | integrated into `scoring.py` | Surprise weighting from event type base rates |
| Source Accuracy | `services/aggregation/source_accuracy.py` | Historical prediction accuracy tracking per source |
| Entropy Detector | integrated into `bayesian.py` | Shannon entropy for mixed signal detection |
| EV Gate | integrated into `eligibility.py` | Expected value computation for recommendation eligibility |
### Modified Modules
| Module | File | Changes |
|--------|------|---------|
| Signal Scorer | `services/aggregation/scoring.py` | Sigmoid gate, info gain factor, adaptive decay, regime multiplier, source accuracy factor |
| Trend Assembler | `services/aggregation/worker.py` | Bayesian confidence, entropy-based direction, regime-adjusted thresholds, entropy-based contradiction |
| Contradiction | `services/aggregation/contradiction.py` | Weighted disagreement entropy replacing minority/majority ratio |
| Macro Scorer | `services/aggregation/interpolation.py` | Multiplicative exposure formula, conditional integration mode |
| Competitive Scorer | `services/aggregation/signal_propagation.py` | Graph-distance attenuation with historical correlation |
| Projection Engine | `services/aggregation/projection.py` | Exponentially weighted momentum, volatility scaling |
| Recommendation | `services/recommendation/eligibility.py` | EV gate, P_bull-based position sizing adjustments |
| Config | `services/shared/config.py` | New probabilistic config parameters |
| Schemas | `services/shared/schemas.py` | Optional new fields on TrendSummary, Recommendation |
### Component Interface Details
#### 1. Bayesian Accumulator (`services/aggregation/bayesian.py`)
```python
@dataclass(frozen=True)
class BayesianPosterior:
"""Bayesian posterior state from signal accumulation."""
p_bull: float # σ(L_t), bullish probability [0, 1]
alpha: float # Beta distribution α parameter (≥ 1.0)
beta: float # Beta distribution β parameter (≥ 1.0)
log_likelihood: float # Raw log-likelihood accumulation L_t
bayesian_confidence: float # 1 - 4αβ/(α+β)², [0, 1]
entropy: float # Shannon entropy H, [0, 1]
signal_count: int # Number of signals processed
# Uninformative prior (no evidence)
PRIOR = BayesianPosterior(
p_bull=0.5, alpha=1.0, beta=1.0,
log_likelihood=0.0, bayesian_confidence=0.0,
entropy=1.0, signal_count=0,
)
def compute_bayesian_posterior(
signals: list[WeightedSignal],
) -> BayesianPosterior:
"""Accumulate weighted signals into a Bayesian posterior.
Computes:
- Log-likelihood: L_t = Σ(w_i · s_i)
- Bullish probability: P_bull = σ(L_t)
- Beta posterior: α = 1 + W_bull, β = 1 + W_bear
- Bayesian confidence: C = 1 - 4αβ/(α+β)²
- Shannon entropy: H = -p·log₂(p) - (1-p)·log₂(1-p)
"""
...
def compute_entropy(p_bull: float) -> float:
"""Shannon entropy H = -p·log₂(p) - (1-p)·log₂(1-p).
Returns value in [0, 1]. Maximum at p=0.5, zero at p=0 or p=1.
Handles edge cases p=0 and p=1 by returning 0.0.
"""
...
```
#### 2. Regime Detector (`services/aggregation/regime.py`)
```python
class MarketRegime(str, Enum):
TREND_FOLLOWING = "trend_following"
PANIC = "panic"
MEAN_REVERSION = "mean_reversion"
UNCERTAINTY = "uncertainty"
@dataclass(frozen=True)
class RegimeClassification:
"""Result of regime detection for a ticker."""
regime: MarketRegime
trend_indicator: float # R = sign(EMA_20 - EMA_100)
volatility_ratio: float # V_r = σ_20 / σ_100
bullish_threshold: float # Adjusted ±threshold for direction
bearish_threshold: float
contradiction_penalty_multiplier: float # 0.4 default, 0.6 for uncertainty
@dataclass(frozen=True)
class RegimeConfig:
ema_short_period: int = 20
ema_long_period: int = 100
vol_short_period: int = 20
vol_long_period: int = 100
panic_vol_ratio: float = 1.5
trend_vol_ratio: float = 1.2
mean_reversion_vol_ratio: float = 1.0
default_threshold: float = 0.15
panic_threshold: float = 0.10
mean_reversion_threshold: float = 0.20
uncertainty_contradiction_multiplier: float = 0.6
def classify_regime(
closing_prices: list[float],
returns: list[float],
config: RegimeConfig = RegimeConfig(),
) -> RegimeClassification:
"""Classify market regime from price and return history.
Requires at least 100 days of price history for EMA_100.
Falls back to UNCERTAINTY when data is insufficient.
"""
...
def compute_ema(values: list[float], period: int) -> float:
"""Compute exponential moving average over the last `period` values."""
...
```
#### 3. Source Accuracy Tracker (`services/aggregation/source_accuracy.py`)
```python
@dataclass
class SourceAccuracy:
"""Per-source historical prediction accuracy."""
source_id: str
accuracy_ratio: float # [0, 1] fraction of correct directional calls
sample_count: int # Number of signals with known outcomes
last_updated: datetime
@property
def accuracy_factor(self) -> float:
"""Multiplicative factor for credibility weight.
Returns 1.0 (neutral) when sample_count < 10.
Otherwise scales linearly from 0.5 (0% accuracy) to 1.5 (100% accuracy).
"""
if self.sample_count < 10:
return 1.0
return 0.5 + self.accuracy_ratio
async def fetch_source_accuracy(
pool: asyncpg.Pool,
source_ids: list[str],
) -> dict[str, SourceAccuracy]:
"""Fetch accuracy metrics for a batch of sources."""
...
async def update_source_accuracy(
pool: asyncpg.Pool,
source_id: str,
realized_outcomes: list[tuple[str, float]], # (predicted_direction, actual_7d_return)
) -> None:
"""Update accuracy metrics for a source based on realized price data."""
...
```
#### 4. Extended ScoringConfig
New fields added to the existing `ScoringConfig` dataclass in `scoring.py`:
```python
@dataclass(frozen=True)
class ScoringConfig:
# ... existing fields preserved ...
# Probabilistic scoring toggle (mirrors feature flag for local use)
probabilistic: bool = False
# Sigmoid gate parameters
sigmoid_steepness: float = 5.0 # k in σ(k·(x - midpoint))
sigmoid_midpoint: float = 0.5 # midpoint of sigmoid transition
# Information gain parameters
info_gain_lambda: float = 0.3 # scaling parameter λ
info_gain_max: float = 3.0 # maximum clamp for info gain factor
default_base_rate: float = 0.1 # fallback when event type rate unknown
# Adaptive decay parameters (β scaling factors)
adaptive_decay_impact_scale: float = 1.0 # max β_impact
adaptive_decay_surprise_scale: float = 1.0 # max β_surprise at r=3.0
adaptive_decay_market_scale: float = 0.5 # max β_market_reaction
# Regime multiplier parameters
regime_return_weight: float = 0.15 # coefficient for |z_r|
regime_volume_weight: float = 0.10 # coefficient for |z_v|
regime_multiplier_max: float = 2.5 # M_regime ceiling
```
#### 5. Extended WeightedSignal
The existing `WeightedSignal` dataclass gains optional fields:
```python
@dataclass
class WeightedSignal:
"""A document intelligence reference paired with its computed weight."""
document_id: str
weight: SignalWeight
sentiment_value: float
impact_score: float
# New optional fields for probabilistic mode
info_gain_factor: float = 1.0 # r = 1 + λ·(-log₂ P(event_type))
source_accuracy_factor: float = 1.0 # [0.5, 1.5] from historical accuracy
adaptive_half_life: float | None = None # τ_i when adaptive decay is active
```
#### 6. Extended SignalWeight
```python
@dataclass
class SignalWeight:
"""Breakdown of a document's aggregation weight."""
recency: float
credibility: float
novelty_bonus: float
confidence_gate: float
market_ctx_multiplier: float
combined: float
# New optional fields for probabilistic mode
sigmoid_gate: float | None = None # Smooth gate value [0, 1]
info_gain_factor: float = 1.0 # Surprise multiplier
source_accuracy_factor: float = 1.0 # Historical accuracy multiplier
regime_multiplier: float | None = None # M_regime replacing M_context
```
#### 7. Extended TrendSummary
New optional fields on the existing Pydantic model:
```python
class TrendSummary(BaseModel):
# ... all existing fields preserved ...
# New optional fields for probabilistic mode
p_bull: float | None = None # Bayesian bullish probability
alpha: float | None = None # Beta posterior α
beta_param: float | None = None # Beta posterior β (named to avoid shadowing)
bayesian_confidence: float | None = None # 1 - 4αβ/(α+β)²
entropy: float | None = None # Shannon entropy H
regime: str | None = None # Market regime classification
pipeline_mode: str = "heuristic" # "heuristic" or "probabilistic"
```
#### 8. Extended Recommendation
```python
class Recommendation(BaseModel):
# ... all existing fields preserved ...
# New optional fields for probabilistic mode
expected_value: float | None = None # EV = P_bull·R_up - P_bear·R_down
p_bull: float | None = None # Bayesian bullish probability used
pipeline_mode: str = "heuristic" # "heuristic" or "probabilistic"
```
---
## Data Models
### Database Storage Strategy
All new mathematical outputs are stored in existing JSONB columns. No new database migrations are required.
#### trend_windows table
The `market_context` JSONB column (currently stores volatility/volume data) is extended to include probabilistic outputs:
```json
{
"volatility": 1.23,
"volume_change_pct": 45.2,
"price_change_pct": -2.1,
"probabilistic": {
"p_bull": 0.72,
"alpha": 8.3,
"beta": 3.1,
"log_likelihood": 0.94,
"bayesian_confidence": 0.61,
"entropy": 0.42,
"regime": "trend_following",
"regime_volatility_ratio": 0.85,
"pipeline_mode": "probabilistic",
"contradiction_entropy": 0.31,
"macro_modifier": 1.15
}
}
```
#### recommendations table
The existing `invalidation_conditions` JSONB column stores recommendation-level data. The new EV and probabilistic fields are stored in a new key within the existing decision trace flow. Since recommendations don't have a dedicated metadata JSONB column, we add the probabilistic fields to the thesis text and store structured data in the `risk_checks` JSONB column of the `recommendation_evaluations` table:
```json
{
"ev": 0.0082,
"p_bull": 0.72,
"r_up": 0.034,
"r_down": 0.012,
"pipeline_mode": "probabilistic",
"ev_threshold": 0.005
}
```
#### risk_configs table
The `config` JSONB column gains the new feature flag:
```json
{
"macro_enabled": true,
"competitive_enabled": true,
"probabilistic_scoring_enabled": false
}
```
#### source_accuracy table (new — Requirement 4)
This is the one new database table required, stored via a migration:
```sql
CREATE TABLE IF NOT EXISTS source_accuracy (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
source_id VARCHAR(200) NOT NULL,
accuracy_ratio FLOAT NOT NULL DEFAULT 0.5,
sample_count INTEGER NOT NULL DEFAULT 0,
last_updated TIMESTAMPTZ NOT NULL DEFAULT NOW(),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE(source_id)
);
CREATE INDEX idx_source_accuracy_source ON source_accuracy(source_id);
```
Note: This is the only schema addition. All other new outputs use existing JSONB columns.
### Event Type Base Rates
Information gain computation requires empirical base rates for event types. These are stored as a configuration constant (not in the database) and can be tuned over time:
```python
EVENT_TYPE_BASE_RATES: dict[str, float] = {
"earnings": 0.25, # Quarterly, common
"product_launch": 0.10, # Moderately rare
"regulatory": 0.08, # Somewhat rare
"legal": 0.05, # Rare
"m_and_a": 0.03, # Very rare
"management_change": 0.06,
"partnership": 0.12,
"market_expansion": 0.09,
"restructuring": 0.04,
"dividend": 0.15,
}
DEFAULT_BASE_RATE = 0.1 # For unknown event types
```
### Configuration Hierarchy
```
risk_configs.config (DB, runtime)
└── probabilistic_scoring_enabled: bool
└── AggregationConfig.probabilistic: bool (in-memory)
└── ScoringConfig.probabilistic: bool (per-cycle)
├── scoring.py: sigmoid vs binary gate
├── scoring.py: adaptive vs fixed decay
├── scoring.py: info gain factor
├── scoring.py: regime multiplier vs market context
├── worker.py: Bayesian vs heuristic confidence
├── worker.py: entropy vs threshold direction
├── contradiction.py: entropy vs ratio
├── interpolation.py: multiplicative vs linear
├── signal_propagation.py: graph-distance vs flat
├── projection.py: EW momentum vs simple
└── eligibility.py: EV gate vs threshold-only
```
---
## Correctness Properties
*A property is a characteristic or behavior that should hold true across all valid executions of a system — essentially, a formal statement about what the system should do. Properties serve as the bridge between human-readable specifications and machine-verifiable correctness guarantees.*
The following properties were derived from the acceptance criteria through systematic prework analysis. Each property is universally quantified and maps to specific requirements. Redundant properties were consolidated during reflection (e.g., requirements 17.117.7 duplicate properties already stated in requirements 115).
### Property 1: Sigmoid Gate Monotonicity
*For any* two extraction confidence values x₁, x₂ ∈ [0.0, 1.0] where x₁ ≤ x₂, the sigmoid gate σ(5·(x₁ - 0.5)) SHALL be less than or equal to σ(5·(x₂ - 0.5)). Higher confidence always produces equal or higher gate values.
**Validates: Requirements 2.6, 17.1**
### Property 2: Beta Posterior Evidence Accumulation
*For any* sequence of weighted signal sets where each successive set contains one additional signal, the sum α + β of the Beta posterior parameters SHALL increase monotonically. Evidence always accumulates — adding a signal never reduces the total evidence mass.
**Validates: Requirements 1.3, 17.2**
### Property 3: Bayesian Confidence Symmetry and Divergence
*For any* Beta posterior with parameters α, β ≥ 1.0, the Bayesian confidence C = 1 - 4αβ/(α+β)² SHALL equal 0.0 when α = β (maximum uncertainty) and SHALL increase monotonically as the ratio max(α/β, β/α) increases. Confidence reflects evidence concentration, not evidence volume.
**Validates: Requirements 1.4, 17.3**
### Property 4: Bayesian Posterior Round-Trip Consistency
*For any* set of weighted signals with uniform weights, computing the Beta posterior and extracting the mean P_bull = α/(α+β) SHALL produce a value within 0.05 of σ(L_t) where L_t is the log-likelihood accumulation. The two probabilistic representations are consistent.
**Validates: Requirements 1.7, 17.7**
### Property 5: Adaptive Decay Lower Bound
*For any* valid combination of impact_score ∈ [0, 1], information gain factor r ∈ [1.0, 3.0], and market context multiplier ∈ [1.0, 1.45], the adaptive half-life τ_i SHALL be greater than or equal to the base half-life τ_base. Adaptive decay is always slower or equal to fixed decay, never faster.
**Validates: Requirements 5.7, 17.4**
### Property 6: Information Gain Monotonicity
*For any* two event type base rates p₁, p₂ ∈ (0, 1] where p₁ < p₂, the information gain factor r(p₁) SHALL be greater than or equal to r(p₂). Rarer events always receive higher surprise weight.
**Validates: Requirements 3.5**
### Property 7: Multiplicative Macro Exposure Monotonicity
*For any* overlap configuration (O_geo, O_supply, O_commodity, O_sector) and any dimension k where O_k = 0, setting O_k to any positive value SHALL increase the total macro impact score. Multi-dimensional exposure always compounds — it never reduces impact.
**Validates: Requirements 10.7, 17.5**
### Property 8: Shannon Entropy Range and Maximum
*For any* bullish probability P_bull ∈ (0, 1), the Shannon entropy H = -P_bull·log₂(P_bull) - (1-P_bull)·log₂(1-P_bull) SHALL be in the range (0, 1], with the maximum value of 1.0 occurring at P_bull = 0.5.
**Validates: Requirements 9.7**
### Property 9: Contradiction Entropy Monotonicity
*For any* set of weighted signals containing both positive and negative sentiment signals, the contradiction entropy score SHALL increase monotonically as the weight distribution f_pos approaches 0.5 (equal split). More balanced disagreement always produces higher contradiction.
**Validates: Requirements 15.7**
### Property 10: Exponentially Weighted Momentum Direction
*For any* sequence of monotonically increasing signed trend strengths (each ΔS_{t-k} > 0), the exponentially weighted momentum M_t SHALL be positive. Consistently strengthening bullish trends always produce positive momentum.
**Validates: Requirements 13.6, 17.6**
### Property 11: Competitive Signal Distance Attenuation
*For any* source-target company pair with fixed source signal strength S_source and historical correlation ρ_historical, the transfer strength S_transfer SHALL decrease monotonically with increasing graph distance d_network. Closer competitors always receive stronger signal transfer.
**Validates: Requirements 12.7**
### Property 12: Expected Value Directional Consistency
*For any* Bayesian bullish probability P_bull > 0.5 and estimated returns where R_up > R_down, the expected value EV = P_bull · R_up - (1 - P_bull) · R_down SHALL be positive. When the model is bullish and upside exceeds downside, EV is always positive.
**Validates: Requirements 17.8**
### Property 13: Bayesian Confidence Monotonic with Agreeing Signals
*For any* set of weighted signals where all signals agree on direction (all positive or all negative), adding one more agreeing signal SHALL increase the Bayesian confidence C. More agreeing evidence always increases confidence.
**Validates: Requirements 8.6**
### Property 14: Numerical Stability Across All Formulas
*For any* valid input combination to any formula in the probabilistic pipeline (sigmoid gate, Beta posterior, Bayesian confidence, adaptive decay, regime multiplier, Shannon entropy, multiplicative exposure, EW momentum, expected value), the output SHALL be a finite float (not NaN, not infinity) within the documented range for that formula. This includes regime multiplier M_regime ∈ [1.0, 2.5], entropy H ∈ [0, 1], P_bull ∈ [0, 1], confidence ∈ [0, 1], and M_adj ∈ [-2.0, 2.0].
**Validates: Requirements 17.9, 6.4**
---
## Error Handling
### Numerical Edge Cases
| Scenario | Handling |
|----------|----------|
| P_bull = 0.0 or 1.0 (entropy undefined) | Return H = 0.0 (no uncertainty at extremes) |
| σ_20 = 0.0 (zero volatility for momentum scaling) | Use floor max(σ_20, 0.01) per Req 13.4 |
| σ_20 = 0.0 or σ_100 = 0.0 (volatility ratio) | Default to uncertainty regime |
| log₂(0) in entropy computation | Guard with `if p <= 0 or p >= 1: return 0.0` |
| log₂(0) in information gain (base_rate = 0) | Base rates must be > 0; use default 0.1 for unknown |
| Division by zero in z-score (σ = 0) | Use M_regime = 1.0 when σ = 0 |
| Empty signal list | Return uninformative prior (P_bull=0.5, α=1, β=1, C=0) |
| All neutral signals (no positive or negative) | Contradiction = 0.0, direction = neutral |
| Extremely large weights (overflow risk) | Python floats handle up to ~1.8e308; clamp combined weight if needed |
| NaN from upstream data | Validate inputs; skip signals with NaN weight or sentiment |
### Feature Flag Failure Modes
| Failure | Behavior |
|---------|----------|
| `risk_configs` table unreachable | Default to `probabilistic_scoring_enabled = false` (heuristic mode) |
| `config` JSONB missing the key | Default to `false` |
| Invalid value type for flag | Default to `false`, log warning |
| Flag changes mid-cycle | Flag is read once at cycle start; change takes effect next cycle |
### Source Accuracy Failures
| Failure | Behavior |
|---------|----------|
| `source_accuracy` table unreachable | Use neutral factor 1.0 for all sources |
| Accuracy update fails | Log error, continue with stale accuracy data |
| Corrupted accuracy data (ratio > 1.0 or < 0.0) | Clamp to [0.0, 1.0] |
### Regime Detection Failures
| Failure | Behavior |
|---------|----------|
| Market data unavailable | Default to uncertainty regime with default thresholds |
| Insufficient price history (< 100 days) | Default to uncertainty regime |
| Price data contains gaps | Use available data; EMA computation handles gaps gracefully |
---
## Testing Strategy
### Dual Testing Approach
The signal math upgrade requires both property-based tests (for mathematical correctness) and example-based unit tests (for specific behaviors and integration points). Property-based testing is highly appropriate here because the feature consists primarily of pure mathematical functions with clear input/output behavior, universal properties that hold across wide input spaces, and well-defined range invariants.
### Property-Based Testing
**Library:** Hypothesis (already in use per `.hypothesis/` directory and project conventions)
**Configuration:**
- Minimum 100 iterations per property: `@settings(max_examples=100)`
- File naming: `test_pbt_signal_math.py` (or split by module)
- Tag format: `# Feature: signal-math-upgrade, Property N: <title>`
**Property tests to implement (one test per correctness property):**
| Property | Test File | Key Generators |
|----------|-----------|----------------|
| 1: Sigmoid monotonicity | `test_pbt_signal_math.py` | `st.floats(0.0, 1.0)` pairs |
| 2: Evidence accumulation | `test_pbt_signal_math.py` | `st.lists(weighted_signal_strategy)` |
| 3: Confidence symmetry/divergence | `test_pbt_signal_math.py` | `st.floats(1.0, 100.0)` for α, β |
| 4: Posterior round-trip | `test_pbt_signal_math.py` | `st.lists(uniform_weight_signal_strategy)` |
| 5: Adaptive decay lower bound | `test_pbt_signal_math.py` | `st.floats` for impact, surprise, market |
| 6: Info gain monotonicity | `test_pbt_signal_math.py` | `st.floats(0.001, 1.0)` pairs |
| 7: Macro exposure monotonicity | `test_pbt_signal_math.py` | `st.floats(0.0, 1.0)` for overlaps |
| 8: Entropy range/maximum | `test_pbt_signal_math.py` | `st.floats(0.001, 0.999)` for P_bull |
| 9: Contradiction monotonicity | `test_pbt_signal_math.py` | Signal sets with varying weight splits |
| 10: EW momentum direction | `test_pbt_signal_math.py` | `st.lists(st.floats)` monotonic sequences |
| 11: Distance attenuation | `test_pbt_signal_math.py` | `st.integers(1, 3)` for distance |
| 12: EV directional consistency | `test_pbt_signal_math.py` | `st.floats(0.5, 1.0)` for P_bull |
| 13: Confidence with agreeing signals | `test_pbt_signal_math.py` | Growing lists of same-direction signals |
| 14: Numerical stability | `test_pbt_signal_math.py` | Broad `st.floats` for all formula inputs |
### Example-Based Unit Tests
**File:** `test_signal_math_unit.py`
| Test Area | Examples |
|-----------|----------|
| Sigmoid gate specific values | x=0.5→0.5, x=0.2→<0.05, x=0.8→>0.95 |
| Uninformative prior | Empty signals → P_bull=0.5, α=1, β=1, C=0 |
| Default base rate | Unknown event type → base_rate=0.1 |
| Info gain clamp | Very rare event → factor ≤ 3.0 |
| Source accuracy threshold | sample_count < 10 → factor=1.0 |
| Adaptive decay edge cases | All zeros → τ_base, all max → 6×τ_base |
| Regime classification | Specific (R, V_r) → expected regime |
| Regime thresholds | panic→0.10, mean_reversion→0.20, etc. |
| Entropy direction mapping | H>0.9→mixed, P_bull>0.65→bullish, etc. |
| Zero overlap → zero impact | All overlaps zero → S_macro=0 |
| Max overlap value | All overlaps 1.0 → ≈severity×0.724 |
| Macro fallback behaviors | Only macro → additive, only company → no modifier |
| Graph distance cutoff | d>3 → no propagation |
| Momentum fallback | <2 cycles → heuristic fallback |
| EV threshold behavior | EV>0.005→proceed, EV≤0.005→informational |
| Feature flag behaviors | flag=false→heuristic, flag=true→probabilistic |
| Heuristic equivalence | flag=false produces identical outputs to current system |
### Integration Tests
| Test Area | Scope |
|-----------|-------|
| Source accuracy persistence | Write/read from source_accuracy table |
| Regime persistence | Store/retrieve regime in JSONB |
| EV persistence | Store/retrieve EV in recommendation_evaluations |
| Feature flag reading | Read probabilistic_scoring_enabled from risk_configs |
| End-to-end pipeline | Full aggregation cycle with probabilistic=true |
### Test Organization
```
tests/
├── test_pbt_signal_math.py # All 14 property-based tests
├── test_signal_math_unit.py # Example-based unit tests
├── test_bayesian.py # Bayesian accumulator unit tests
├── test_regime.py # Regime detector unit tests
├── test_source_accuracy.py # Source accuracy tracker tests
└── test_signal_math_integration.py # Integration tests (DB required)
```
@@ -0,0 +1,293 @@
# Requirements Document — Signal Math Upgrade
## Introduction
The Stonks Oracle platform uses a three-layer signal aggregation engine (company-specific, macro, competitive) to produce market intelligence and drive paper-trading decisions. The current mathematical models are structurally too deterministic and too linear for a market system that is fundamentally probabilistic, regime-dependent, and nonlinear. The pipeline behaves as weighted sentiment aggregation with heuristics rather than a probabilistic forecasting engine.
This feature upgrades the signal processing mathematics across all pipeline stages — from signal scoring through trend assembly, macro impact, competitive signals, trend projection, and recommendation generation — to replace heuristic formulas with probabilistic, regime-aware, and adaptive alternatives. The goal is to transform prediction quality while preserving the existing `WeightedSignal` abstraction, three-layer architecture, and database schema compatibility.
## Glossary
- **Aggregation_Engine**: The core pipeline in `services/aggregation/worker.py` that merges signals from all three layers and computes `TrendSummary` objects across five time windows.
- **Signal_Scorer**: The scoring module in `services/aggregation/scoring.py` that transforms raw intelligence records into `WeightedSignal` objects with composite aggregation weights.
- **Trend_Assembler**: The component in `services/aggregation/worker.py` that derives trend direction, strength, confidence, and contradiction from merged weighted signals.
- **Macro_Scorer**: The macro impact scoring module in `services/aggregation/interpolation.py` that computes per-company impact from global events using overlap-based exposure profiles.
- **Competitive_Scorer**: The competitive signal modules in `services/aggregation/pattern_matcher.py` and `services/aggregation/signal_propagation.py` that mine historical patterns and propagate cross-company signals.
- **Projection_Engine**: The trend projection module in `services/aggregation/projection.py` that computes forward-looking trend estimates from momentum and macro decay.
- **Recommendation_Engine**: The recommendation pipeline in `services/recommendation/` that translates trend assessments into actionable buy/sell/hold/watch decisions with position sizing.
- **WeightedSignal**: The core data abstraction pairing a document reference with a composite aggregation weight, sentiment value, and impact score.
- **Beta_Distribution**: A probability distribution on [0, 1] parameterized by α and β, used to model the posterior probability of bullish vs bearish sentiment.
- **Regime_Detector**: A new component that classifies the current market regime (trend-following, panic, mean-reversion, uncertainty) from price and volume statistics.
- **Sigmoid_Function**: The logistic function σ(x) = 1/(1+e^(-x)) used to convert log-likelihood accumulations into probabilities.
- **Adaptive_Decay**: A recency decay mechanism where the half-life varies per signal based on event impact, surprise, and market reaction rather than using a fixed constant per window.
- **Information_Gain**: A measure of how surprising an event is relative to its base rate, computed as -log P(event_type), used to weight novel signals more heavily.
- **Entropy**: Shannon entropy H = -p·log(p) - (1-p)·log(1-p), used to detect mixed sentiment states where the probability distribution is spread rather than concentrated.
- **EMA**: Exponential Moving Average, a weighted moving average giving more weight to recent observations, used for trend and volatility regime detection.
---
## Requirements
### Requirement 1: Probabilistic Sentiment Accumulation via Bayesian Evidence
**User Story:** As a quantitative analyst, I want the signal scoring layer to accumulate sentiment evidence probabilistically using Bayesian methods, so that the system captures uncertainty structure instead of collapsing sentiment into binary ±1 labels.
#### Acceptance Criteria
1. WHEN a set of weighted signals is provided for a ticker and window, THE Signal_Scorer SHALL compute a log-likelihood accumulation L_t = Σ(w_i · s_i) where w_i is the combined signal weight and s_i is the sentiment value.
2. WHEN the log-likelihood L_t has been computed, THE Signal_Scorer SHALL convert the accumulation to a bullish probability using the Sigmoid_Function: P_bull = σ(L_t) = 1/(1+e^(-L_t)).
3. WHEN weighted signals are provided, THE Signal_Scorer SHALL maintain a Beta_Distribution posterior with parameters α_t = α_0 + W_bull and β_t = β_0 + W_bear, where W_bull is the sum of combined weights for positive signals and W_bear is the sum for negative signals, and α_0 = β_0 = 1.0 as uninformative priors.
4. THE Signal_Scorer SHALL compute Bayesian confidence from the Beta_Distribution posterior variance as C = 1 - 4αβ/(α+β)², where C ranges from 0.0 (maximum uncertainty at α=β) to approaching 1.0 (strong evidence concentration).
5. WHEN no signals exist for a ticker and window, THE Signal_Scorer SHALL return P_bull = 0.5, α = 1.0, β = 1.0, and C = 0.0, representing the uninformative prior state.
6. THE Signal_Scorer SHALL preserve the existing `WeightedSignal` dataclass interface, adding the Bayesian posterior fields (P_bull, α, β, Bayesian confidence) as additional output alongside the existing weighted sentiment average.
7. FOR ALL valid sets of weighted signals, computing the Beta posterior then extracting P_bull SHALL produce a value within 0.05 of σ(L_t) when signal weights are uniform (round-trip consistency between the two probabilistic representations).
---
### Requirement 2: Sigmoid Confidence Gate Replacing Binary Gate
**User Story:** As a quantitative analyst, I want the binary confidence gate replaced with a smooth sigmoid transition, so that marginally confident signals contribute proportionally rather than being completely discarded or fully included.
#### Acceptance Criteria
1. WHEN a document signal has extraction confidence x, THE Signal_Scorer SHALL compute a soft gate value p = σ(5·(x - 0.5)) = 1/(1+e^(-5·(x-0.5))) instead of the current binary 0/1 gate.
2. WHEN extraction confidence is 0.5, THE Signal_Scorer SHALL produce a gate value of 0.5 (the sigmoid midpoint).
3. WHEN extraction confidence is below 0.2, THE Signal_Scorer SHALL produce a gate value below 0.05, preserving near-zero weight for very low confidence signals.
4. WHEN extraction confidence is above 0.8, THE Signal_Scorer SHALL produce a gate value above 0.95, preserving near-full weight for high confidence signals.
5. THE Signal_Scorer SHALL use the sigmoid gate value as a multiplicative factor in the combined weight formula in place of the current binary G_conf.
6. FOR ALL extraction confidence values in [0.0, 1.0], THE Signal_Scorer SHALL produce gate values that are monotonically increasing (higher confidence always produces equal or higher gate values).
---
### Requirement 3: Information Gain Surprise Weighting
**User Story:** As a quantitative analyst, I want signals weighted by their information gain (surprise factor), so that rare and unexpected events receive proportionally higher influence than routine signals.
#### Acceptance Criteria
1. WHEN a signal has a known event type (e.g., earnings, product_launch, regulatory, legal, m_and_a), THE Signal_Scorer SHALL compute an information gain factor r = 1 + λ·(-log₂ P(event_type)), where P(event_type) is the empirical base rate of that event type and λ is a configurable scaling parameter with default 0.3.
2. WHEN the event type base rate is not available, THE Signal_Scorer SHALL use a default base rate of 0.1 (treating the event as moderately rare).
3. THE Signal_Scorer SHALL multiply the information gain factor r into the combined weight formula as an additional multiplicative component.
4. THE Signal_Scorer SHALL clamp the information gain factor to a maximum of 3.0 to prevent extremely rare events from dominating the aggregation.
5. FOR ALL event types with base rate in (0, 1], THE Signal_Scorer SHALL produce information gain factors that are monotonically decreasing with increasing base rate (rarer events always receive higher surprise weight).
---
### Requirement 4: Historical Source Accuracy Tracking
**User Story:** As a quantitative analyst, I want source credibility to incorporate historical prediction accuracy, so that sources with a track record of correct directional calls receive higher weight.
#### Acceptance Criteria
1. THE Signal_Scorer SHALL maintain a per-source accuracy metric computed as the fraction of past signals from that source where the predicted direction matched the subsequent 7-day price movement direction.
2. WHEN a source has at least 10 historical signals with known outcomes, THE Signal_Scorer SHALL incorporate the source accuracy as a multiplicative factor on the credibility weight, scaled linearly from 0.5 (0% accuracy) to 1.5 (100% accuracy).
3. WHEN a source has fewer than 10 historical signals, THE Signal_Scorer SHALL use a neutral accuracy factor of 1.0 (no adjustment).
4. THE Signal_Scorer SHALL update source accuracy metrics asynchronously after each aggregation cycle, using realized price data from the market data tables.
5. THE Signal_Scorer SHALL store source accuracy metrics in a database table with columns for source identifier, accuracy ratio, sample count, and last updated timestamp.
---
### Requirement 5: Adaptive Recency Decay with Event-Specific Half-Lives
**User Story:** As a quantitative analyst, I want recency decay half-lives to adapt based on event characteristics, so that high-impact events persist longer in the aggregation while routine signals decay faster.
#### Acceptance Criteria
1. WHEN computing recency decay for a signal, THE Signal_Scorer SHALL use an adaptive half-life τ_i = τ_base · (1 + β_impact) · (1 + β_surprise) · (1 + β_market_reaction), where τ_base is the current fixed half-life for the window.
2. THE Signal_Scorer SHALL compute β_impact from the signal's impact score, scaled linearly from 0.0 (impact_score = 0) to 1.0 (impact_score = 1.0).
3. THE Signal_Scorer SHALL compute β_surprise from the information gain factor (Requirement 3), scaled linearly from 0.0 (r = 1.0, no surprise) to 1.0 (r = 3.0, maximum surprise).
4. THE Signal_Scorer SHALL compute β_market_reaction from the market context multiplier, scaled linearly from 0.0 (multiplier = 1.0, no market reaction) to 0.5 (multiplier = 1.45, maximum market reaction).
5. WHEN all three β factors are at their maximum, THE Signal_Scorer SHALL produce an adaptive half-life of at most 6× the base half-life (τ_base · 2.0 · 2.0 · 1.5 = 6.0 · τ_base).
6. WHEN all three β factors are zero (routine, unsurprising signal in calm market), THE Signal_Scorer SHALL produce the same half-life as the current fixed system (τ_base).
7. FOR ALL combinations of impact, surprise, and market reaction values, THE Signal_Scorer SHALL produce adaptive half-lives that are greater than or equal to τ_base (adaptive decay is always slower or equal to the base decay, never faster).
---
### Requirement 6: Volatility-Adjusted Normalization (Regime-Aware Scoring)
**User Story:** As a quantitative analyst, I want signal weights normalized by current market volatility and volume conditions, so that the same signal magnitude is interpreted differently in calm vs volatile markets.
#### Acceptance Criteria
1. WHEN market data is available for a ticker, THE Signal_Scorer SHALL compute a return z-score z_r = (r_t - μ_20) / σ_20, where r_t is the current return, μ_20 is the 20-day mean return, and σ_20 is the 20-day return standard deviation.
2. WHEN market data is available for a ticker, THE Signal_Scorer SHALL compute a volume z-score z_v = (log(V_t) - μ_V) / σ_V, where V_t is the current volume, μ_V is the 20-day mean of log-volume, and σ_V is the 20-day standard deviation of log-volume.
3. THE Signal_Scorer SHALL compute a regime multiplier M_regime = 1 + 0.15·|z_r| + 0.10·|z_v|, which amplifies signal weights during abnormal market conditions.
4. THE Signal_Scorer SHALL clamp M_regime to the range [1.0, 2.5] to prevent extreme z-scores from producing runaway weight amplification.
5. WHEN market data is not available for a ticker, THE Signal_Scorer SHALL use M_regime = 1.0 (no regime adjustment).
6. THE Signal_Scorer SHALL replace the current market context multiplier (M_context) with M_regime in the combined weight formula.
---
### Requirement 7: Regime Detection and Classification
**User Story:** As a quantitative analyst, I want the system to detect and classify the current market regime for each ticker, so that scoring thresholds and behavior adapt to whether the market is trending, panicking, mean-reverting, or uncertain.
#### Acceptance Criteria
1. WHEN market data is available, THE Regime_Detector SHALL compute a trend indicator R = sign(EMA_20 - EMA_100), where EMA_20 and EMA_100 are exponential moving averages of closing prices over 20 and 100 days respectively.
2. WHEN market data is available, THE Regime_Detector SHALL compute a volatility ratio V_r = σ_20 / σ_100, where σ_20 and σ_100 are the 20-day and 100-day return standard deviations.
3. THE Regime_Detector SHALL classify the market regime into one of four categories based on R and V_r: trend-following (R ≠ 0 AND V_r < 1.2), panic (V_r > 1.5), mean-reversion (R = 0 AND V_r < 1.0), uncertainty (all other cases).
4. WHEN the regime is classified as panic, THE Aggregation_Engine SHALL reduce the bullish/bearish threshold from ±0.15 to ±0.10 (making the system more sensitive to directional signals during high-volatility periods).
5. WHEN the regime is classified as mean-reversion, THE Aggregation_Engine SHALL increase the bullish/bearish threshold from ±0.15 to ±0.20 (requiring stronger evidence for directional calls in range-bound markets).
6. WHEN the regime is classified as trend-following, THE Aggregation_Engine SHALL use the default thresholds of ±0.15.
7. WHEN the regime is classified as uncertainty, THE Aggregation_Engine SHALL use the default thresholds of ±0.15 and increase the contradiction penalty multiplier from 0.4 to 0.6.
8. THE Regime_Detector SHALL persist the current regime classification per ticker to the database for auditability and dashboard display.
9. WHEN market data is insufficient to compute EMA_100 (fewer than 100 days of price history), THE Regime_Detector SHALL default to the uncertainty regime.
---
### Requirement 8: Bayesian Posterior Confidence Replacing Heuristic Confidence
**User Story:** As a quantitative analyst, I want trend confidence derived from the Bayesian posterior distribution rather than the current heuristic weighted formula, so that confidence reflects actual evidence concentration rather than an ad-hoc combination of factors.
#### Acceptance Criteria
1. WHEN computing trend confidence, THE Trend_Assembler SHALL use the Bayesian confidence C = 1 - 4αβ/(α+β)² from the Beta_Distribution posterior (Requirement 1) as the primary confidence component with weight 0.5.
2. THE Trend_Assembler SHALL retain the source count factor (min(N_unique/15, 0.8)) as a secondary confidence component with weight 0.25, rewarding evidence breadth.
3. THE Trend_Assembler SHALL retain the contradiction penalty (contradiction_score × 0.4) as a confidence reduction.
4. THE Trend_Assembler SHALL compute the combined confidence as: confidence = 0.5 × C_bayesian + 0.25 × F_count + 0.25 × C_avg_credibility - P_contradiction, clamped to [0.0, 1.0].
5. THE Trend_Assembler SHALL preserve the existing confidence thresholds for recommendation eligibility (0.35 minimum, 0.50 paper, 0.70 live) without modification.
6. FOR ALL signal sets where all signals agree on direction, THE Trend_Assembler SHALL produce Bayesian confidence that increases monotonically with the number of agreeing signals.
---
### Requirement 9: Entropy-Based Mixed Signal Detection
**User Story:** As a quantitative analyst, I want mixed trend detection based on Shannon entropy rather than simple contradiction thresholds, so that the system can distinguish between genuine uncertainty (high entropy) and weak signal (low total weight).
#### Acceptance Criteria
1. WHEN the bullish probability P_bull has been computed from the Bayesian posterior, THE Trend_Assembler SHALL compute Shannon entropy H = -P_bull·log₂(P_bull) - (1-P_bull)·log₂(1-P_bull).
2. WHEN H > 0.9 (entropy close to maximum of 1.0, indicating near-equal probability of bullish and bearish), THE Trend_Assembler SHALL classify the trend direction as mixed, regardless of the weighted sentiment average.
3. WHEN H ≤ 0.9 AND P_bull > 0.65, THE Trend_Assembler SHALL classify the trend direction as bullish.
4. WHEN H ≤ 0.9 AND P_bull < 0.35, THE Trend_Assembler SHALL classify the trend direction as bearish.
5. WHEN H ≤ 0.9 AND 0.35 ≤ P_bull ≤ 0.65, THE Trend_Assembler SHALL classify the trend direction as neutral.
6. THE Trend_Assembler SHALL persist the entropy value H alongside the trend summary for auditability.
7. FOR ALL P_bull values in (0, 1), THE Trend_Assembler SHALL compute entropy values in (0, 1], with maximum entropy of 1.0 occurring at P_bull = 0.5.
---
### Requirement 10: Multiplicative Macro Exposure Scoring
**User Story:** As a quantitative analyst, I want macro impact computed using multiplicative exposure rather than linear weighted sums, so that a company exposed across multiple dimensions receives compounding impact rather than simple addition.
#### Acceptance Criteria
1. WHEN computing macro impact for a company, THE Macro_Scorer SHALL use the multiplicative exposure formula S_macro = severity · (1 - Π_k(1 - w_k · O_k)), where O_k are the overlap components (geographic, supply chain, commodity, sector) and w_k are their respective weights.
2. THE Macro_Scorer SHALL use the following overlap weights: w_geo = 0.35, w_supply = 0.25, w_commodity = 0.25, w_sector = 0.15 (matching the current linear weight distribution).
3. WHEN a company has zero overlap across all dimensions, THE Macro_Scorer SHALL produce S_macro = 0.0 (no impact).
4. WHEN a company has maximum overlap across all dimensions (all O_k = 1.0), THE Macro_Scorer SHALL produce S_macro = severity · (1 - (1-0.35)·(1-0.25)·(1-0.25)·(1-0.15)), which is approximately severity · 0.724.
5. THE Macro_Scorer SHALL preserve the existing severity weight mapping (critical=1.0, high=0.75, moderate=0.5, low=0.25).
6. THE Macro_Scorer SHALL preserve the existing resilience modifier (R_tier) applied after the multiplicative exposure computation.
7. FOR ALL overlap configurations, THE Macro_Scorer SHALL produce impact scores where adding a non-zero overlap in any dimension increases the total impact (monotonicity property).
---
### Requirement 11: Conditional Macro Signal Integration
**User Story:** As a quantitative analyst, I want macro signals treated as conditional modifiers on company signals rather than additive contributions, so that macro context amplifies or dampens existing company-level evidence rather than independently shifting the trend.
#### Acceptance Criteria
1. WHEN both company signals and macro signals exist for a ticker, THE Aggregation_Engine SHALL apply macro impact as a multiplicative modifier on the company signal strength: S_adjusted = S_company · (1 + M_macro · sign_alignment), where M_macro is the normalized macro impact and sign_alignment is +1 when macro and company signals agree in direction, -1 when they disagree.
2. THE Aggregation_Engine SHALL clamp the macro modifier (1 + M_macro · sign_alignment) to the range [0.5, 1.5] to prevent macro signals from inverting or excessively amplifying company signals.
3. WHEN only macro signals exist (no company signals), THE Aggregation_Engine SHALL fall back to the current additive behavior with the existing macro weight of 0.3, preserving the macro-only suppression safety mechanism.
4. WHEN only company signals exist (macro layer disabled or no macro events), THE Aggregation_Engine SHALL use company signals without modification (modifier = 1.0).
5. THE Aggregation_Engine SHALL log the macro modifier value applied to each ticker for auditability.
---
### Requirement 12: Graph-Distance Competitive Signal Attenuation
**User Story:** As a quantitative analyst, I want competitive signal transfer attenuated by network graph distance and historical correlation, so that signals propagate more strongly to closely related competitors and decay for distant relationships.
#### Acceptance Criteria
1. WHEN propagating a signal from a source company to a target company, THE Competitive_Scorer SHALL compute transfer strength as S_transfer = S_source · ρ_historical · e^(-d_network), where S_source is the source signal strength, ρ_historical is the historical price correlation between the two companies, and d_network is the graph distance in the competitor relationship network.
2. THE Competitive_Scorer SHALL compute graph distance d_network as the shortest path length in the competitor relationship graph, where direct competitors have distance 1, competitors-of-competitors have distance 2, and so on.
3. WHEN the graph distance exceeds 3, THE Competitive_Scorer SHALL not propagate the signal (e^(-3) ≈ 0.05, below meaningful contribution).
4. THE Competitive_Scorer SHALL compute ρ_historical as the 90-day rolling Pearson correlation of daily returns between the source and target companies.
5. WHEN historical correlation data is insufficient (fewer than 30 trading days of overlapping data), THE Competitive_Scorer SHALL use a default correlation of 0.3 for same-sector companies and 0.1 for cross-sector companies.
6. THE Competitive_Scorer SHALL preserve the existing relationship strength threshold (R_relationship ≥ 0.2) as a pre-filter before applying the graph-distance attenuation.
7. FOR ALL source-target pairs, THE Competitive_Scorer SHALL produce transfer strengths that decrease monotonically with increasing graph distance (closer competitors always receive stronger signal transfer).
---
### Requirement 13: Exponentially Weighted Momentum
**User Story:** As a quantitative analyst, I want trend momentum computed using exponentially weighted historical changes rather than a simple current-minus-previous difference, so that the momentum estimate is smoother and less sensitive to single-cycle noise.
#### Acceptance Criteria
1. WHEN computing trend momentum, THE Projection_Engine SHALL use an exponentially weighted sum M_t = Σ_{k=0}^{K-1} λ^k · ΔS_{t-k}, where ΔS_{t-k} is the signed strength change at lag k, λ = 0.7 is the decay factor, and K is the number of available historical cycles (up to 10).
2. THE Projection_Engine SHALL normalize the momentum by dividing by the geometric series sum Σ λ^k to produce a value in [-1, 1].
3. WHEN fewer than 2 historical cycles are available, THE Projection_Engine SHALL fall back to the current heuristic (momentum = direction_sign × strength × 0.5).
4. THE Projection_Engine SHALL compute volatility-scaled momentum M_adj = M_t / max(σ_20, 0.01), where σ_20 is the 20-day return standard deviation, to normalize momentum relative to the ticker's typical price movement.
5. THE Projection_Engine SHALL clamp M_adj to [-2.0, 2.0] to prevent division by very small σ_20 from producing extreme values.
6. FOR ALL sequences of monotonically increasing signed strengths, THE Projection_Engine SHALL produce positive momentum values (correctly detecting strengthening bullish trends).
---
### Requirement 14: Expected Value Recommendation Gate
**User Story:** As a quantitative analyst, I want recommendation eligibility based on expected value rather than simple confidence and strength thresholds, so that the system only recommends trades with positive risk-adjusted expected outcomes.
#### Acceptance Criteria
1. WHEN evaluating recommendation eligibility, THE Recommendation_Engine SHALL compute expected value EV = P_bull · R_up - P_bear · R_down, where P_bull is the Bayesian bullish probability, P_bear = 1 - P_bull, R_up is the estimated upside return, and R_down is the estimated downside return.
2. THE Recommendation_Engine SHALL estimate R_up and R_down from the trend strength and the ticker's 20-day historical volatility: R_up = strength · σ_20 · √(horizon_days) and R_down = (1 - strength) · σ_20 · √(horizon_days), where horizon_days corresponds to the trend window duration.
3. WHEN EV is positive and exceeds a configurable threshold (default 0.005, representing 0.5% expected return), THE Recommendation_Engine SHALL allow the recommendation to proceed through the existing eligibility gates.
4. WHEN EV is negative or below the threshold, THE Recommendation_Engine SHALL force the recommendation to informational mode regardless of confidence and strength.
5. THE Recommendation_Engine SHALL persist the computed EV alongside the recommendation for auditability.
6. THE Recommendation_Engine SHALL preserve all existing eligibility gates (confidence ≥ 0.35, strength ≥ 0.10, contradiction ≤ 0.60, evidence ≥ 2, direction ≠ neutral) as additional requirements beyond the EV gate.
---
### Requirement 15: Contradiction Handling via Weighted Disagreement Entropy
**User Story:** As a quantitative analyst, I want contradiction detection to use weighted disagreement entropy rather than a simple minority/majority ratio, so that the system better distinguishes between a few strong dissenting signals and many weak ones.
#### Acceptance Criteria
1. WHEN computing contradiction, THE Trend_Assembler SHALL compute weighted disagreement entropy using the effective weight distribution across positive and negative signal groups.
2. THE Trend_Assembler SHALL compute the positive weight fraction f_pos = W_positive / (W_positive + W_negative) and negative weight fraction f_neg = W_negative / (W_positive + W_negative), where W_positive and W_negative are the sums of effective weights (combined_weight × impact_score) for each sentiment group.
3. THE Trend_Assembler SHALL compute contradiction entropy as H_contradiction = -f_pos·log₂(f_pos) - f_neg·log₂(f_neg), normalized to [0, 1] (maximum at f_pos = f_neg = 0.5).
4. THE Trend_Assembler SHALL weight the contradiction entropy by the total evidence mass: contradiction_score = H_contradiction · min(1.0, (W_positive + W_negative) / W_threshold), where W_threshold is a configurable parameter (default 5.0) representing the evidence mass at which contradiction becomes fully significant.
5. WHEN only positive or only negative signals exist (no disagreement), THE Trend_Assembler SHALL produce a contradiction score of 0.0.
6. THE Trend_Assembler SHALL preserve the existing `ContradictionResult` interface, populating the overall score with the entropy-based value and retaining the `DisagreementDetail` objects for catalyst-level analysis.
7. FOR ALL signal sets with both positive and negative signals, THE Trend_Assembler SHALL produce contradiction scores that increase monotonically as the weight distribution approaches equal split (f_pos → 0.5).
---
### Requirement 16: Backward Compatibility and Migration
**User Story:** As a platform operator, I want the mathematical upgrades to be backward-compatible with the existing database schema and deployable incrementally, so that the upgrade does not require downtime or data migration.
#### Acceptance Criteria
1. THE Aggregation_Engine SHALL preserve the existing `WeightedSignal`, `SignalWeight`, `TrendSummary`, and `Recommendation` dataclass interfaces, adding new fields as optional attributes with default values.
2. THE Aggregation_Engine SHALL store new mathematical outputs (P_bull, α, β, entropy, regime, EV) in the existing JSONB metadata fields of `trend_windows` and `recommendations` tables rather than requiring new columns.
3. THE Aggregation_Engine SHALL support a feature flag `probabilistic_scoring_enabled` in `risk_configs` that toggles between the current heuristic pipeline and the new probabilistic pipeline, defaultable to `false` for safe rollout.
4. WHEN `probabilistic_scoring_enabled` is false, THE Aggregation_Engine SHALL produce identical outputs to the current system (no behavioral change).
5. WHEN `probabilistic_scoring_enabled` is true, THE Aggregation_Engine SHALL use the new Bayesian, regime-aware, and adaptive formulas for all pipeline stages.
6. IF the feature flag toggle fails to read from the database, THEN THE Aggregation_Engine SHALL default to the current heuristic pipeline (fail-safe behavior).
7. THE Aggregation_Engine SHALL log which pipeline mode (heuristic or probabilistic) is active at the start of each aggregation cycle.
---
### Requirement 17: Property-Based Testing for Mathematical Correctness
**User Story:** As a developer, I want comprehensive property-based tests validating the mathematical correctness of all new formulas, so that edge cases and numerical stability issues are caught before deployment.
#### Acceptance Criteria
1. THE test suite SHALL include property-based tests using Hypothesis for the sigmoid confidence gate verifying monotonicity (higher confidence input always produces higher or equal gate output) across all float inputs in [0.0, 1.0].
2. THE test suite SHALL include property-based tests for the Beta_Distribution posterior verifying that α + β increases monotonically with the number of signals processed (evidence always accumulates).
3. THE test suite SHALL include property-based tests for the Bayesian confidence formula verifying that confidence is 0.0 when α = β (maximum uncertainty) and approaches 1.0 as the ratio α/β or β/α increases.
4. THE test suite SHALL include property-based tests for the adaptive decay verifying that the adaptive half-life is always greater than or equal to the base half-life for all valid input combinations.
5. THE test suite SHALL include property-based tests for the multiplicative macro exposure verifying monotonicity (adding non-zero overlap in any dimension increases total impact).
6. THE test suite SHALL include property-based tests for the exponentially weighted momentum verifying that monotonically increasing strength sequences produce positive momentum.
7. THE test suite SHALL include a round-trip property test verifying that computing the Beta posterior from signals, extracting P_bull, then reconstructing approximate signal weights produces values consistent with the original inputs.
8. THE test suite SHALL include property-based tests for the expected value computation verifying that EV is positive when P_bull > 0.5 and R_up > R_down (basic directional consistency).
9. THE test suite SHALL include property-based tests for numerical stability verifying that no formula produces NaN, infinity, or values outside documented ranges for any valid input combination.
10. THE test suite SHALL use `@settings(max_examples=100)` and follow the project convention of `test_pbt_*` file naming.
+349
View File
@@ -0,0 +1,349 @@
# Implementation Plan: Signal Math Upgrade
## Overview
Upgrade the Stonks Oracle signal processing pipeline from deterministic heuristic formulas to a probabilistic, regime-aware, and adaptive mathematical framework. Implementation proceeds in layers: foundations (config, schemas, new modules), then each pipeline stage (scoring → trend assembly → macro → competitive → projection → recommendation), then integration wiring, and finally testing. All changes are gated behind the `probabilistic_scoring_enabled` feature flag.
## Tasks
- [ ] 1. Foundation: Configuration and schema extensions
- [x] 1.1 Extend `ScoringConfig` with probabilistic parameters in `services/aggregation/scoring.py`
- Add `probabilistic: bool = False` toggle field
- Add sigmoid gate parameters: `sigmoid_steepness`, `sigmoid_midpoint`
- Add information gain parameters: `info_gain_lambda`, `info_gain_max`, `default_base_rate`
- Add adaptive decay parameters: `adaptive_decay_impact_scale`, `adaptive_decay_surprise_scale`, `adaptive_decay_market_scale`
- Add regime multiplier parameters: `regime_return_weight`, `regime_volume_weight`, `regime_multiplier_max`
- All new fields must have defaults matching the design document values
- _Requirements: 2.5, 3.1, 5.1, 6.3, 16.1_
- [x] 1.2 Extend `SignalWeight` and `WeightedSignal` dataclasses in `services/aggregation/scoring.py`
- Add optional fields to `SignalWeight`: `sigmoid_gate`, `info_gain_factor`, `source_accuracy_factor`, `regime_multiplier`
- Add optional fields to `WeightedSignal`: `info_gain_factor`, `source_accuracy_factor`, `adaptive_half_life`
- All new fields must have defaults (None or 1.0) for backward compatibility
- _Requirements: 16.1, 2.5, 3.3, 4.2_
- [x] 1.3 Extend `TrendSummary` Pydantic model in `services/shared/schemas.py`
- Add optional fields: `p_bull`, `alpha`, `beta_param`, `bayesian_confidence`, `entropy`, `regime`, `pipeline_mode`
- `pipeline_mode` defaults to `"heuristic"`; all others default to `None`
- _Requirements: 16.1, 1.6, 9.6_
- [x] 1.4 Extend `Recommendation` model in `services/shared/schemas.py` (or `services/recommendation/eligibility.py`)
- Add optional fields: `expected_value`, `p_bull`, `pipeline_mode`
- `pipeline_mode` defaults to `"heuristic"`; all others default to `None`
- _Requirements: 16.1, 14.5_
- [x] 1.5 Add `probabilistic_scoring_enabled` feature flag support in `services/shared/config.py`
- Read `probabilistic_scoring_enabled` from `risk_configs.config` JSONB
- Default to `False` when key is missing, value is invalid, or DB is unreachable
- Propagate flag through `AggregationConfig` dataclass
- Log which pipeline mode is active at cycle start
- _Requirements: 16.3, 16.4, 16.5, 16.6, 16.7_
- [x] 1.6 Create database migration `infra/migrations/034_source_accuracy.sql`
- Create `source_accuracy` table with columns: `id UUID PRIMARY KEY DEFAULT gen_random_uuid()`, `source_id VARCHAR(200) NOT NULL`, `accuracy_ratio FLOAT NOT NULL DEFAULT 0.5`, `sample_count INTEGER NOT NULL DEFAULT 0`, `last_updated TIMESTAMPTZ`, `created_at TIMESTAMPTZ`
- Add `UNIQUE(source_id)` constraint and `idx_source_accuracy_source` index
- _Requirements: 4.5_
- [x] 2. Checkpoint — Verify foundation compiles and existing tests pass
- Ensure all tests pass, ask the user if questions arise.
- [ ] 3. New module: Bayesian Accumulator (`services/aggregation/bayesian.py`)
- [x] 3.1 Implement `BayesianPosterior` dataclass and `compute_bayesian_posterior` function
- Create frozen dataclass with fields: `p_bull`, `alpha`, `beta`, `log_likelihood`, `bayesian_confidence`, `entropy`, `signal_count`
- Define `PRIOR` class-level constant for uninformative prior (p_bull=0.5, α=1.0, β=1.0, C=0.0, H=1.0)
- Implement log-likelihood accumulation: `L_t = Σ(w_i · s_i)` using `weight.combined * sentiment_value`
- Compute `P_bull = σ(L_t)` via sigmoid function
- Compute Beta posterior: `α = 1 + W_bull`, `β = 1 + W_bear` from positive/negative weight sums
- Compute Bayesian confidence: `C = 1 - 4αβ/(α+β)²`
- Compute Shannon entropy via `compute_entropy`
- Return `PRIOR` for empty signal lists
- Skip signals with NaN weight or sentiment
- _Requirements: 1.1, 1.2, 1.3, 1.4, 1.5, 1.6_
- [x] 3.2 Implement `compute_entropy` function
- Shannon entropy: `H = -p·log₂(p) - (1-p)·log₂(1-p)`
- Return 0.0 for p ≤ 0 or p ≥ 1 (edge cases)
- Return value in [0, 1] with maximum 1.0 at p=0.5
- _Requirements: 9.1, 9.7_
- [x] 3.3 Write property test for sigmoid gate monotonicity
- **Property 1: Sigmoid Gate Monotonicity**
- **Validates: Requirements 2.6, 17.1**
- [x] 3.4 Write property test for Beta posterior evidence accumulation
- **Property 2: Beta Posterior Evidence Accumulation**
- **Validates: Requirements 1.3, 17.2**
- [x] 3.5 Write property test for Bayesian confidence symmetry and divergence
- **Property 3: Bayesian Confidence Symmetry and Divergence**
- **Validates: Requirements 1.4, 17.3**
- [x] 3.6 Write property test for Bayesian posterior round-trip consistency
- **Property 4: Bayesian Posterior Round-Trip Consistency**
- **Validates: Requirements 1.7, 17.7**
- [x] 3.7 Write property test for Shannon entropy range and maximum
- **Property 8: Shannon Entropy Range and Maximum**
- **Validates: Requirements 9.7**
- [x] 3.8 Write property test for Bayesian confidence monotonic with agreeing signals
- **Property 13: Bayesian Confidence Monotonic with Agreeing Signals**
- **Validates: Requirements 8.6**
- [ ] 4. New module: Regime Detector (`services/aggregation/regime.py`)
- [x] 4.1 Implement `MarketRegime` enum, `RegimeClassification` and `RegimeConfig` dataclasses
- `MarketRegime`: `TREND_FOLLOWING`, `PANIC`, `MEAN_REVERSION`, `UNCERTAINTY`
- `RegimeClassification`: `regime`, `trend_indicator`, `volatility_ratio`, `bullish_threshold`, `bearish_threshold`, `contradiction_penalty_multiplier`
- `RegimeConfig`: all configurable parameters with defaults from design
- _Requirements: 7.3_
- [x] 4.2 Implement `compute_ema` and `classify_regime` functions
- `compute_ema`: exponential moving average over last N values
- `classify_regime`: compute trend indicator `R = sign(EMA_20 - EMA_100)` and volatility ratio `V_r = σ_20 / σ_100`
- Classification rules: trend-following (R≠0 AND V_r<1.2), panic (V_r>1.5), mean-reversion (R=0 AND V_r<1.0), uncertainty (all other)
- Adjust thresholds per regime: panic→±0.10, mean-reversion→±0.20, trend-following→±0.15, uncertainty→±0.15 with contradiction multiplier 0.6
- Default to uncertainty when data is insufficient (<100 days) or σ values are zero
- _Requirements: 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.9_
- [ ] 5. New module: Source Accuracy Tracker (`services/aggregation/source_accuracy.py`)
- [x] 5.1 Implement `SourceAccuracy` dataclass and database functions
- `SourceAccuracy` dataclass with `source_id`, `accuracy_ratio`, `sample_count`, `last_updated`
- `accuracy_factor` property: return 1.0 when sample_count < 10, else `0.5 + accuracy_ratio`
- `fetch_source_accuracy`: batch fetch from `source_accuracy` table via asyncpg
- `update_source_accuracy`: update accuracy metrics from realized price outcomes
- Handle DB unreachable: return neutral factor 1.0 for all sources
- Clamp corrupted accuracy_ratio to [0.0, 1.0]
- _Requirements: 4.1, 4.2, 4.3, 4.4, 4.5_
- [x] 6. Checkpoint — Verify new modules compile and unit tests pass
- Ensure all tests pass, ask the user if questions arise.
- [ ] 7. Signal Scorer upgrades (`services/aggregation/scoring.py`)
- [x] 7.1 Implement sigmoid confidence gate
- Add `sigmoid_gate(x, steepness, midpoint)` function: `σ(k·(x - midpoint))`
- When `probabilistic=True`, replace binary gate with sigmoid gate in `compute_signal_weight`
- When `probabilistic=False`, preserve existing binary gate behavior
- _Requirements: 2.1, 2.2, 2.3, 2.4, 2.5_
- [x] 7.2 Implement information gain surprise weighting
- Add `EVENT_TYPE_BASE_RATES` constant dict and `DEFAULT_BASE_RATE = 0.1`
- Add `compute_info_gain(event_type, lambda_param, max_gain, default_base_rate)` function: `r = 1 + λ·(-log₂ P(event_type))`, clamped to max 3.0
- Integrate as multiplicative factor in combined weight when `probabilistic=True`
- _Requirements: 3.1, 3.2, 3.3, 3.4, 3.5_
- [x] 7.3 Implement adaptive recency decay
- Add `compute_adaptive_half_life(base_half_life, impact_score, info_gain_factor, market_multiplier, config)` function
- Compute `β_impact`, `β_surprise`, `β_market_reaction` scaling factors per design
- `τ_i = τ_base · (1 + β_impact) · (1 + β_surprise) · (1 + β_market_reaction)`
- When `probabilistic=True`, use adaptive half-life in `recency_weight`; otherwise use fixed
- _Requirements: 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7_
- [x] 7.4 Implement regime multiplier replacing market context multiplier
- Add `compute_regime_multiplier(returns, volumes, config)` function
- Compute z-scores for return and volume, then `M_regime = 1 + 0.15·|z_r| + 0.10·|z_v|`
- Clamp to [1.0, 2.5]; default to 1.0 when data unavailable or σ=0
- When `probabilistic=True`, use `M_regime` instead of `M_context` in combined weight
- _Requirements: 6.1, 6.2, 6.3, 6.4, 6.5_
- [x] 7.5 Integrate source accuracy factor into `compute_signal_weight`
- Accept optional `source_accuracy_factor` parameter
- When `probabilistic=True`, multiply into combined weight formula
- When `probabilistic=False`, ignore (factor = 1.0)
- _Requirements: 4.2, 4.3_
- [x] 7.6 Update `compute_signal_weight` to branch on `probabilistic` flag
- When `probabilistic=True`: use sigmoid gate × recency (adaptive) × credibility × (1 + novelty) × info_gain × source_accuracy × regime_multiplier
- When `probabilistic=False`: preserve exact current formula (binary gate × recency × credibility × (1 + novelty) × market_context)
- Populate all new optional fields on `SignalWeight` and `WeightedSignal`
- _Requirements: 16.4, 16.5_
- [x] 7.7 Write property test for information gain monotonicity
- **Property 6: Information Gain Monotonicity**
- **Validates: Requirements 3.5**
- [x] 7.8 Write property test for adaptive decay lower bound
- **Property 5: Adaptive Decay Lower Bound**
- **Validates: Requirements 5.7, 17.4**
- [ ] 8. Contradiction upgrade (`services/aggregation/contradiction.py`)
- [x] 8.1 Implement weighted disagreement entropy contradiction
- Compute `f_pos = W_positive / (W_positive + W_negative)` and `f_neg = 1 - f_pos`
- Compute `H_contradiction = -f_pos·log₂(f_pos) - f_neg·log₂(f_neg)`
- Weight by evidence mass: `contradiction_score = H_contradiction · min(1.0, (W_pos + W_neg) / W_threshold)`
- Return 0.0 when only one direction exists
- Preserve existing `ContradictionResult` interface
- When `probabilistic=False`, preserve existing minority/majority ratio behavior
- _Requirements: 15.1, 15.2, 15.3, 15.4, 15.5, 15.6, 15.7_
- [x] 8.2 Write property test for contradiction entropy monotonicity
- **Property 9: Contradiction Entropy Monotonicity**
- **Validates: Requirements 15.7**
- [ ] 9. Trend Assembly upgrades (`services/aggregation/worker.py`)
- [x] 9.1 Integrate Bayesian posterior into trend assembly
- When `probabilistic=True`, call `compute_bayesian_posterior` on merged signals
- Use Bayesian confidence formula for trend confidence: `0.5 × C_bayesian + 0.25 × F_count + 0.25 × C_avg_credibility - P_contradiction`
- Use entropy-based direction: H>0.9→mixed, P_bull>0.65→bullish, P_bull<0.35→bearish, else neutral
- Apply regime-adjusted thresholds from `RegimeClassification`
- Populate new `TrendSummary` fields: `p_bull`, `alpha`, `beta_param`, `bayesian_confidence`, `entropy`, `regime`, `pipeline_mode`
- Store probabilistic outputs in `market_context` JSONB under `"probabilistic"` key
- When `probabilistic=False`, preserve exact current heuristic behavior
- _Requirements: 1.1, 1.2, 8.1, 8.2, 8.3, 8.4, 8.5, 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 7.8, 16.4, 16.5_
- [x] 9.2 Wire regime detection into the aggregation cycle
- Call `classify_regime` with closing prices and returns for each ticker
- Pass `RegimeClassification` to trend assembly for threshold adjustment
- Default to uncertainty regime when market data is unavailable
- Persist regime classification in JSONB for auditability
- _Requirements: 7.1, 7.2, 7.3, 7.8, 7.9_
- [ ] 10. Macro scoring upgrade (`services/aggregation/interpolation.py`)
- [x] 10.1 Implement multiplicative macro exposure formula
- When `probabilistic=True`, compute `S_macro = severity · (1 - Π_k(1 - w_k · O_k))` instead of linear weighted sum
- Preserve overlap weights: w_geo=0.35, w_supply=0.25, w_commodity=0.25, w_sector=0.15
- Preserve severity mapping and resilience modifier
- When `probabilistic=False`, preserve exact current linear formula
- _Requirements: 10.1, 10.2, 10.3, 10.4, 10.5, 10.6_
- [x] 10.2 Implement conditional macro signal integration
- When `probabilistic=True` and both company and macro signals exist, apply macro as multiplicative modifier: `S_adjusted = S_company · clamp(1 + M_macro · sign_alignment, 0.5, 1.5)`
- When only macro signals exist, fall back to additive behavior with weight 0.3
- When only company signals exist, use modifier = 1.0
- Log macro modifier value per ticker
- When `probabilistic=False`, preserve current additive merge behavior
- _Requirements: 11.1, 11.2, 11.3, 11.4, 11.5_
- [x] 10.3 Write property test for multiplicative macro exposure monotonicity
- **Property 7: Multiplicative Macro Exposure Monotonicity**
- **Validates: Requirements 10.7, 17.5**
- [ ] 11. Competitive signal upgrade (`services/aggregation/signal_propagation.py`)
- [x] 11.1 Implement graph-distance attenuation for competitive signals
- When `probabilistic=True`, compute `S_transfer = S_source · ρ_historical · e^(-d_network)` instead of flat transfer
- Compute graph distance as shortest path in competitor relationship graph (cap at 3)
- Use 90-day rolling Pearson correlation for `ρ_historical`; default to 0.3 (same-sector) or 0.1 (cross-sector) when insufficient data (<30 days)
- Preserve existing relationship strength threshold (R ≥ 0.2) as pre-filter
- When `probabilistic=False`, preserve exact current flat transfer behavior
- _Requirements: 12.1, 12.2, 12.3, 12.4, 12.5, 12.6, 12.7_
- [x] 11.2 Write property test for competitive signal distance attenuation
- **Property 11: Competitive Signal Distance Attenuation**
- **Validates: Requirements 12.7**
- [ ] 12. Projection upgrade (`services/aggregation/projection.py`)
- [x] 12.1 Implement exponentially weighted momentum
- When `probabilistic=True`, compute `M_t = Σ_{k=0}^{K-1} λ^k · ΔS_{t-k}` with λ=0.7, K up to 10
- Normalize by geometric series sum to produce value in [-1, 1]
- Fall back to current heuristic when fewer than 2 historical cycles available
- Compute volatility-scaled momentum: `M_adj = M_t / max(σ_20, 0.01)`, clamped to [-2.0, 2.0]
- When `probabilistic=False`, preserve exact current simple momentum behavior
- _Requirements: 13.1, 13.2, 13.3, 13.4, 13.5, 13.6_
- [x] 12.2 Write property test for exponentially weighted momentum direction
- **Property 10: Exponentially Weighted Momentum Direction**
- **Validates: Requirements 13.6, 17.6**
- [ ] 13. Recommendation upgrade (`services/recommendation/eligibility.py`)
- [x] 13.1 Implement expected value recommendation gate
- When `probabilistic=True`, compute `EV = P_bull · R_up - P_bear · R_down`
- Estimate `R_up = strength · σ_20 · √(horizon_days)` and `R_down = (1 - strength) · σ_20 · √(horizon_days)`
- When EV > threshold (default 0.005), allow recommendation through existing gates
- When EV ≤ threshold, force recommendation to informational mode
- Persist EV in `risk_checks` JSONB of `recommendation_evaluations`
- Populate `expected_value`, `p_bull`, `pipeline_mode` on Recommendation model
- Preserve all existing eligibility gates as additional requirements
- When `probabilistic=False`, skip EV gate entirely
- _Requirements: 14.1, 14.2, 14.3, 14.4, 14.5, 14.6_
- [x] 13.2 Write property test for expected value directional consistency
- **Property 12: Expected Value Directional Consistency**
- **Validates: Requirements 17.8**
- [x] 14. Checkpoint — Verify all pipeline stages compile and existing tests still pass
- Ensure all tests pass, ask the user if questions arise.
- [ ] 15. Integration wiring and feature flag plumbing
- [x] 15.1 Wire feature flag through the aggregation worker entry point
- Read `probabilistic_scoring_enabled` from `risk_configs` at cycle start in `services/aggregation/worker.py`
- Pass flag to `ScoringConfig`, trend assembly, contradiction, macro, competitive, and projection stages
- Log pipeline mode at cycle start
- Ensure flag is read once per cycle (mid-cycle changes take effect next cycle)
- _Requirements: 16.3, 16.6, 16.7_
- [x] 15.2 Wire source accuracy fetch into the scoring pipeline
- At cycle start, batch-fetch source accuracy for all source IDs in the current signal set
- Pass `source_accuracy_factor` to `compute_signal_weight` for each signal
- Handle DB errors gracefully (default to 1.0)
- _Requirements: 4.1, 4.2, 4.3_
- [x] 15.3 Wire regime detection into the aggregation cycle
- Fetch closing prices and returns for each ticker from market data
- Call `classify_regime` and pass result to trend assembly and scoring stages
- Handle missing market data (default to uncertainty regime)
- _Requirements: 7.1, 7.8, 7.9_
- [x] 15.4 Store probabilistic outputs in existing JSONB columns
- Store Bayesian fields in `trend_windows.market_context` JSONB under `"probabilistic"` key
- Store EV fields in `recommendation_evaluations.risk_checks` JSONB
- Store regime classification in trend window JSONB
- _Requirements: 16.2_
- [ ] 16. Numerical stability and edge case hardening
- [x] 16.1 Add input validation and edge case guards across all new functions
- Guard `log₂(0)` in entropy and information gain computations
- Floor `max(σ_20, 0.01)` for momentum volatility scaling
- Default to uncertainty regime when σ values are zero
- Return `M_regime = 1.0` when z-score σ = 0
- Skip signals with NaN weight or sentiment
- Clamp all outputs to documented ranges
- _Requirements: 17.9, 6.4_
- [x] 16.2 Write property test for numerical stability across all formulas
- **Property 14: Numerical Stability Across All Formulas**
- **Validates: Requirements 17.9, 6.4**
- [ ] 17. Unit tests for all new and modified modules
- [x] 17.1 Write unit tests for Bayesian accumulator (`tests/test_bayesian.py`)
- Test uninformative prior (empty signals → P_bull=0.5, α=1, β=1, C=0)
- Test specific sigmoid gate values (x=0.5→0.5, x=0.2→<0.05, x=0.8→>0.95)
- Test entropy direction mapping (H>0.9→mixed, P_bull>0.65→bullish, etc.)
- _Requirements: 1.1, 1.2, 1.3, 1.4, 1.5_
- [x] 17.2 Write unit tests for regime detector (`tests/test_regime.py`)
- Test specific (R, V_r) → expected regime classification
- Test threshold adjustments per regime (panic→0.10, mean_reversion→0.20)
- Test insufficient data fallback to uncertainty
- _Requirements: 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.9_
- [x] 17.3 Write unit tests for source accuracy tracker (`tests/test_source_accuracy.py`)
- Test accuracy_factor property: sample_count < 10 → 1.0, else 0.5 + ratio
- Test corrupted data clamping
- _Requirements: 4.1, 4.2, 4.3_
- [x] 17.4 Write unit tests for signal scoring upgrades (`tests/test_signal_math_unit.py`)
- Test info gain clamp (very rare event → factor ≤ 3.0)
- Test default base rate (unknown event type → 0.1)
- Test adaptive decay edge cases (all zeros → τ_base, all max → 6×τ_base)
- Test zero overlap → zero macro impact
- Test max overlap → ≈severity×0.724
- Test macro fallback behaviors (only macro → additive, only company → no modifier)
- Test graph distance cutoff (d>3 → no propagation)
- Test momentum fallback (<2 cycles → heuristic)
- Test EV threshold behavior (EV>0.005→proceed, EV≤0.005→informational)
- Test feature flag behaviors (flag=false→heuristic, flag=true→probabilistic)
- _Requirements: 3.1, 3.4, 5.5, 5.6, 10.3, 10.4, 11.3, 13.3, 14.3, 14.4, 16.4, 16.5_
- [x] 18. Final checkpoint — Ensure all tests pass
- Ensure all tests pass, ask the user if questions arise.
## Notes
- Tasks marked with `*` are optional and can be skipped for faster MVP
- Each task references specific requirements for traceability
- Checkpoints ensure incremental validation after each major phase
- Property tests validate the 14 universal correctness properties from the design document
- Unit tests validate specific examples, edge cases, and integration points
- The design uses Python throughout — no language selection needed
- Migration number is 034 (existing migrations go up to 033)
- All new dataclass fields use optional defaults for backward compatibility
- Feature flag `probabilistic_scoring_enabled` gates every behavioral change
+12 -12
View File
@@ -30,18 +30,16 @@
- Ruff config: `ruff.toml` with `known-first-party = ["services"]` for consistent import sorting
- Pre-existing test failures (not regressions): `test_extractor_prompts.py`, `test_extractor_schemas.py`, `test_filings_adapter.py`, `test_ollama_client.py`
## CI/CD — GitHub Actions
- Workflow: `.github/workflows/build.yml`
- Triggers on push to `main` and PRs
- Jobs:
- `lint-and-test`: ruff lint + pytest + frontend vitest (Node 24)
- `build-services`: matrix build of all Python services → GHCR
- `build-dashboard`: frontend/Dockerfile → GHCR (TypeScript strict mode — catches unused imports)
- `build-superset`: docker/Dockerfile.superset → GHCR
## CI/CD — Woodpecker CI (Gitea) → GitHub promotion
- Woodpecker pipelines in `.woodpecker/` — triggered by push to `main` on Gitea
- Push to Gitea: `git push gitea main`
- Gitea remote: `http://admin:<password>@10.1.1.12:30300/admin/stonks-oracle.git`
- Pipeline stages: lint pytest frontend vitest → build all service images + dashboard + superset → push to Harbor
- ArgoCD watches Gitea `main` and auto-syncs beta/paper/live stages
- **Do NOT push directly to GitHub** — GitHub is the promotion target after CI passes
- Once Woodpecker builds and tests pass, code is promoted to GitHub (`git push origin main`)
- CI handles all image builds and pushes — do NOT manually docker push
- Check CI: `gh run list -L 3`
- Re-run failed: `gh run rerun <id> --failed`
- View failure logs: `gh run view <id> --log-failed`
- Check Woodpecker CI status from the Gitea web UI or Woodpecker dashboard
## Deploy
- Full deploy/redeploy: `bash ~/sources/kube/stonks-oracle/runmefirst.sh` (from gremlin-1)
@@ -74,7 +72,9 @@ Ingestion jobs MUST include `source_id`, `source_type`, `ticker`, `company_id`,
## Git Conventions
- Commit after each completed phase task
- Commit message format: `feat:`, `fix:`, `phase N:` prefix
- Push to `main` triggers CI
- Always push to Gitea: `git push gitea main`
- Do NOT push to GitHub (`origin`) directly — GitHub is the promotion target after CI passes
- ArgoCD syncs from Gitea automatically
## Code Style
- Python 3.12, type hints everywhere
+8 -5
View File
@@ -40,14 +40,17 @@ Three-layer signal aggregation engine:
- Container registry: `registry.celestium.life/stonks-oracle`
## CI/CD
- GitHub Actions workflow at `.github/workflows/build.yml`
- Push to `main` triggers: lint → pytest → frontend vitest → build all service images + dashboard + superset → push to Harbor
- Woodpecker CI pipelines in `.woodpecker/` — triggered by push to `main` on Gitea
- Push to Gitea: `git push gitea main` — this is the primary push target
- ArgoCD watches Gitea `main` and auto-syncs beta/paper/live stages
- Pipeline stages: lint → pytest → frontend vitest → build all service images + dashboard + superset → push to Harbor
- Images tagged as `registry.celestium.life/stonks-oracle/<service>:<sha>` and `:latest`
- Dashboard image: `frontend/Dockerfile` (multi-stage: node:24 → nginx-unprivileged on port 8080)
- Superset image: `docker/Dockerfile.superset` (apache/superset + trino + psycopg2)
- Python service images: `docker/Dockerfile` with `SERVICE_CMD` build arg
- Let CI handle image builds and pushes — do NOT manually `docker build && docker push`
- Check CI status: `gh run list -L 3`
- **Do NOT push directly to GitHub** — GitHub (`origin`) is the promotion target after CI builds and tests pass
- Promotion to GitHub: `git push origin main` (only after Woodpecker CI succeeds)
## Deployment Scripts
- `~/sources/kube/stonks-oracle/runmefirst.sh` — full deploy: DB setup, migrations, Helm install, rolling restart (runs from gremlin-1 at 192.168.42.254 where secrets are available)
@@ -76,9 +79,9 @@ When a full reset is needed:
- Ollama: `ollama.ollama-service.svc.cluster.local:11434` (cluster-internal), also at `http://10.1.1.12:2701` (external), GPU: 4070 Ti Super 16GB
## Database Migrations
- Located in `infra/migrations/001_*.sql` through `027_*.sql`
- Located in `infra/migrations/001_*.sql` through `030_*.sql`
- Applied automatically by `runmefirst.sh` in sorted order
- Next migration number: **029**
- Next migration number: **031**
- Key migrations:
- 016: Global news interpolation (global_events, macro_impact_records, exposure_profiles, trend_projections)
- 017: Competitive intelligence (competitor_relationships, competitive_signal_records)
-20
View File
@@ -24,11 +24,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
@@ -64,11 +59,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
@@ -105,11 +95,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
@@ -146,11 +131,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
-20
View File
@@ -24,11 +24,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
@@ -65,11 +60,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
@@ -106,11 +96,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
@@ -147,11 +132,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
-30
View File
@@ -24,11 +24,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
@@ -65,11 +60,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
@@ -106,11 +96,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
@@ -147,11 +132,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
@@ -188,11 +168,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
@@ -229,11 +204,6 @@ steps:
from_secret: harbor_username
password:
from_secret: harbor_password
- registry: https://index.docker.io/v1/
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- ${CI_COMMIT_SHA}
- latest
+55 -34
View File
@@ -8,6 +8,21 @@ Licensed under the [Business Source License 1.1](LICENSE). Production use requir
AI-powered market intelligence and autonomous paper-trading platform. Ingests market data, company news, and regulatory filings; extracts structured intelligence with local LLMs; aggregates signals across three layers (company, macro, competitive); and autonomously executes paper trades — all self-hosted on Kubernetes.
## Documentation
| Document | Description |
|----------|-------------|
| [Service Reference](docs/services.md) | All 13 services — purpose, configuration, queue topology, database tables |
| [API Reference](docs/api-reference.md) | Complete endpoint reference for Query API, Symbol Registry, Trading, and Risk services |
| [Helm Chart Reference](docs/helm-reference.md) | All Helm values: services, config, secrets, ingress, network policies, analytics stack |
| [Docker Deployment Guide](docs/docker-deployment.md) | Docker Compose setup, environment variables, volumes, operational commands |
| [Kubernetes Architecture](docs/architecture-kubernetes.md) | Mermaid diagram of the K8s deployment topology, namespaces, ingress, and secrets |
| [Docker Compose Architecture](docs/architecture-docker-compose.md) | Mermaid diagram of all containers, port mappings, volumes, and dependencies |
| [Data Pipeline Architecture](docs/architecture-data-pipeline.md) | Mermaid diagram of the end-to-end data pipeline, queue topology, and signal layers |
| [AI Agents Guide](docs/ai-agents.md) | Built-in agents, variant management, prompt tuning, and performance monitoring |
| [Backup & Restore Guide](docs/backup-restore.md) | Backup scripts, restore procedures, retention policies, and disaster recovery |
| [Observability Reference](docs/observability.md) | Prometheus metrics, alerting rules, structured logging, and dead-letter queues |
## What It Does
Stonks Oracle tracks 50 companies across 10 sectors. It monitors multiple data sources, runs every article and filing through a local Ollama model to extract structured intelligence, aggregates those signals into rolling trend summaries with contradiction detection, and generates explainable trade recommendations. An autonomous trading engine then evaluates those recommendations and executes paper trades through Alpaca without manual intervention.
@@ -16,41 +31,47 @@ Everything is auditable — raw artifacts, prompts, model outputs, decision trac
## Architecture
```mermaid
flowchart LR
subgraph sources ["Data Sources"]
polygon["Polygon.io"]
sec["SEC EDGAR"]
macro_src["Macro News"]
end
subgraph pipeline ["Signal Processing"]
scheduler["Scheduler"]
ingestion["Ingestion"]
parser["Parser"]
extractor["Extractor"]
aggregation["Aggregation"]
recommendation["Recommendation"]
end
subgraph trading ["Trading"]
risk["Risk Engine"]
engine["Trading Engine"]
broker["Broker Adapter"]
alpaca["Alpaca (paper)"]
end
subgraph analytics ["Analytics"]
lake["Lake Publisher"]
trino["Trino"]
superset["Superset"]
dashboard["Dashboard"]
end
sources --> scheduler --> ingestion --> parser --> extractor --> aggregation --> recommendation
recommendation --> risk --> engine --> broker --> alpaca
aggregation --> lake --> trino --> superset
trino --> dashboard
```
┌──────────────────────────────────────────┐
│ Signal Aggregation │
│ │
┌───────────┐ ┌──────────┐ │ ┌──────────┐ ┌────────────────┐ │
│ Scheduler │─▶│Ingestion │─▶│ │ Parser │─▶│ Extractor │ │
└───────────┘ └──────────┘ │ └──────────┘ └──────┬─────────┘ │
│ │ │
│ ┌─────────────┘ │
│ ▼ │
│ ┌─────────────┐ ┌────────────────┐ │
│ │ Aggregation │───▶│ Recommendation │ │
│ └──────┬──────┘ └───────┬────────┘ │
│ │ │ │
│ Macro signals Competitive │
│ + Competitive signals │
│ signals merged │
└──────────────────────────────────────────┘
┌───────────────────────┘
┌─────────────┐ ┌────────────────┐ ┌──────────────┐
│ Risk Engine │───▶│ Trading Engine │───▶│Broker Adapter│
└─────────────┘ └────────────────┘ └──────────────┘
┌────────────────┐ ┌──────────┘
│ Lake Publisher │ ▼
└───────┬────────┘ Alpaca (paper)
┌──────────────┼──────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌───────────┐
│ Trino │ │ Superset │ │ Dashboard │
└──────────┘ └──────────┘ └───────────┘
```
For detailed architecture diagrams see:
- [Kubernetes Deployment](docs/architecture-kubernetes.md)
- [Docker Compose Deployment](docs/architecture-docker-compose.md)
- [Data Pipeline](docs/architecture-data-pipeline.md)
Two planes:
- **Operational** — ingestion, parsing, extraction, aggregation, recommendations, risk evaluation, autonomous trading, trade execution (PostgreSQL, Redis, MinIO)
+518
View File
@@ -0,0 +1,518 @@
#!/usr/bin/env bash
set -euo pipefail
# deploy-docker.sh — Deploy Stonks Oracle to a Docker host via SSH
#
# Usage: bash deploy-docker.sh [OPTIONS]
#
# Options:
# --host USER@HOST SSH target (default: celes@192.168.42.254)
# --ollama-url URL Ollama API URL (default: auto-detect or install)
# --ollama-model MODEL Ollama model name (default: qwen3.5:9b-fast)
# --dir PATH Remote install directory (default: ~/stonks-oracle)
#
# Examples:
# bash deploy-docker.sh
# bash deploy-docker.sh --ollama-url http://10.1.1.12:2701 --ollama-model qwen3.6
# bash deploy-docker.sh --host user@myserver --dir /opt/stonks
# -------------------------------------------------------
# Configuration (override via flags or environment)
# -------------------------------------------------------
REMOTE_HOST="${DEPLOY_HOST:-celes@192.168.42.254}"
REMOTE_DIR="${DEPLOY_DIR:-/home/celes/stonks-oracle}"
OLLAMA_URL="${DEPLOY_OLLAMA_URL:-}"
OLLAMA_MODEL="${DEPLOY_OLLAMA_MODEL:-qwen3.5:9b-fast}"
REPO_URL="http://admin:St0nks0racl3!@10.1.1.12:30300/admin/stonks-oracle.git"
# Parse command-line flags
while [[ $# -gt 0 ]]; do
case $1 in
--host) REMOTE_HOST="$2"; shift 2 ;;
--ollama-url) OLLAMA_URL="$2"; shift 2 ;;
--ollama-model) OLLAMA_MODEL="$2"; shift 2 ;;
--dir) REMOTE_DIR="$2"; shift 2 ;;
*) echo "Unknown option: $1"; exit 1 ;;
esac
done
echo "=== Stonks Oracle Docker Deployment ==="
echo " Target: ${REMOTE_HOST}:${REMOTE_DIR}"
echo " Model: ${OLLAMA_MODEL}"
echo " Ollama: Docker container (GPU-accelerated)"
echo ""
# -------------------------------------------------------
# Step 0: Ensure prerequisites (multi-distro support)
# -------------------------------------------------------
echo "--- Step 0: Checking prerequisites ---"
ssh "$REMOTE_HOST" bash -s <<'REMOTE_SCRIPT'
set -euo pipefail
# --- Detect OS and package manager ---
detect_os() {
if [ -f /etc/os-release ]; then
. /etc/os-release
OS_ID="${ID:-unknown}"
OS_LIKE="${ID_LIKE:-$OS_ID}"
elif [ -f /etc/redhat-release ]; then
OS_ID="rhel"
OS_LIKE="rhel"
else
OS_ID="unknown"
OS_LIKE="unknown"
fi
# Detect WSL
IS_WSL=false
if grep -qi microsoft /proc/version 2>/dev/null; then
IS_WSL=true
fi
# Determine package manager
if command -v apt-get &>/dev/null; then
PKG_MGR="apt"
elif command -v dnf &>/dev/null; then
PKG_MGR="dnf"
elif command -v yum &>/dev/null; then
PKG_MGR="yum"
elif command -v pacman &>/dev/null; then
PKG_MGR="pacman"
elif command -v zypper &>/dev/null; then
PKG_MGR="zypper"
else
PKG_MGR="unknown"
fi
echo " Detected: OS=$OS_ID (like=$OS_LIKE), pkg=$PKG_MGR, WSL=$IS_WSL"
}
install_pkg() {
local pkg="$1"
case "$PKG_MGR" in
apt) sudo apt-get install -y "$pkg" ;;
dnf) sudo dnf -y install "$pkg" ;;
yum) sudo yum -y install "$pkg" ;;
pacman) sudo pacman -S --noconfirm "$pkg" ;;
zypper) sudo zypper install -y "$pkg" ;;
*) echo " ERROR: Unknown package manager"; exit 1 ;;
esac
}
update_pkg_cache() {
case "$PKG_MGR" in
apt) sudo apt-get update -qq ;;
dnf|yum) ;; # dnf/yum auto-refresh
pacman) sudo pacman -Sy ;;
zypper) sudo zypper refresh -q ;;
esac
}
detect_os
# --- Git ---
if ! command -v git &>/dev/null; then
echo " Installing git..."
update_pkg_cache
install_pkg git
echo " ✓ Git installed"
else
echo " ✓ Git present"
fi
# --- Docker Engine ---
if command -v docker &>/dev/null && docker info &>/dev/null; then
echo " ✓ Docker already installed ($(docker --version | cut -d' ' -f3 | tr -d ','))"
else
echo " Installing Docker CE..."
case "$PKG_MGR" in
apt)
# Debian/Ubuntu/WSL
sudo apt-get update -qq
sudo apt-get install -y ca-certificates curl gnupg
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/${OS_ID}/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg 2>/dev/null
sudo chmod a+r /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/${OS_ID} $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update -qq
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
;;
dnf|yum)
# RHEL/Rocky/Fedora/CentOS
sudo "$PKG_MGR" -y install dnf-plugins-core 2>/dev/null || true
local repo_distro="rhel"
if [[ "$OS_ID" == "fedora" ]]; then repo_distro="fedora"; fi
sudo dnf config-manager --add-repo "https://download.docker.com/linux/${repo_distro}/docker-ce.repo" 2>/dev/null || \
sudo yum-config-manager --add-repo "https://download.docker.com/linux/${repo_distro}/docker-ce.repo" 2>/dev/null
sudo "$PKG_MGR" -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
;;
pacman)
# Arch Linux
sudo pacman -S --noconfirm docker docker-compose docker-buildx
;;
zypper)
# openSUSE
sudo zypper install -y docker docker-compose docker-buildx
;;
esac
sudo systemctl enable --now docker 2>/dev/null || true
sudo usermod -aG docker "$(whoami)" 2>/dev/null || true
echo " ✓ Docker installed and started"
fi
# --- Docker Compose plugin ---
if docker compose version &>/dev/null; then
echo " ✓ Docker Compose plugin available ($(docker compose version --short))"
else
echo " ERROR: docker compose plugin not found after Docker install"
exit 1
fi
# --- NVIDIA Driver (skip on WSL — uses host driver) ---
if [ "$IS_WSL" = "true" ]; then
echo " ✓ WSL detected — using host Windows NVIDIA driver"
elif ! command -v nvidia-smi &>/dev/null; then
echo " Installing NVIDIA drivers..."
case "$PKG_MGR" in
apt)
sudo apt-get install -y nvidia-driver-560 2>/dev/null || \
sudo apt-get install -y nvidia-driver 2>/dev/null || \
echo " ⚠ NVIDIA driver install failed — install manually"
;;
dnf|yum)
sudo dnf -y install epel-release 2>/dev/null || true
sudo dnf config-manager --add-repo https://developer.download.nvidia.com/compute/cuda/repos/rhel9/x86_64/cuda-rhel9.repo 2>/dev/null || true
sudo dnf -y module install nvidia-driver:latest-dkms 2>/dev/null || \
echo " ⚠ NVIDIA driver install failed — install manually"
;;
pacman)
sudo pacman -S --noconfirm nvidia nvidia-utils 2>/dev/null || \
echo " ⚠ NVIDIA driver install failed — install manually"
;;
zypper)
echo " ⚠ NVIDIA driver: install manually for openSUSE"
;;
esac
else
echo " ✓ NVIDIA driver present ($(nvidia-smi --query-gpu=driver_version --format=csv,noheader | head -1))"
fi
# --- NVIDIA Container Toolkit ---
if command -v nvidia-ctk &>/dev/null; then
echo " ✓ NVIDIA Container Toolkit already installed"
elif [ "$IS_WSL" = "true" ] && docker run --rm --gpus all nvidia/cuda:12.8.0-base-ubuntu24.04 nvidia-smi &>/dev/null 2>&1; then
echo " ✓ WSL GPU passthrough working (no nvidia-ctk needed)"
else
echo " Installing NVIDIA Container Toolkit..."
case "$PKG_MGR" in
apt)
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg 2>/dev/null
curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \
sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list > /dev/null
sudo apt-get update -qq
sudo apt-get install -y nvidia-container-toolkit
;;
dnf|yum)
curl -fsSL https://nvidia.github.io/libnvidia-container/stable/rpm/nvidia-container-toolkit.repo | \
sudo tee /etc/yum.repos.d/nvidia-container-toolkit.repo > /dev/null
sudo "$PKG_MGR" -y install nvidia-container-toolkit
;;
pacman)
sudo pacman -S --noconfirm nvidia-container-toolkit 2>/dev/null || \
echo " ⚠ Install nvidia-container-toolkit from AUR"
;;
zypper)
echo " ⚠ NVIDIA Container Toolkit: install manually for openSUSE"
;;
esac
sudo nvidia-ctk runtime configure --runtime=docker 2>/dev/null || true
sudo systemctl restart docker 2>/dev/null || true
echo " ✓ NVIDIA Container Toolkit installed and Docker configured"
fi
# --- Verify GPU is accessible from Docker ---
if docker run --rm --gpus all nvidia/cuda:12.8.0-base-ubuntu24.04 nvidia-smi &>/dev/null 2>&1; then
echo " ✓ GPU passthrough verified"
else
echo " ⚠ GPU passthrough test failed — may need a reboot or manual NVIDIA setup"
fi
# --- Firewall (open required ports if firewall is active) ---
if command -v firewall-cmd &>/dev/null && systemctl is-active firewalld &>/dev/null; then
echo " Configuring firewalld..."
for port in 3000 8001 8002 8003 8004 9000 9001 11434; do
sudo firewall-cmd --permanent --add-port="${port}/tcp" 2>/dev/null || true
done
sudo firewall-cmd --reload 2>/dev/null || true
echo " ✓ Firewall ports opened"
elif command -v ufw &>/dev/null && sudo ufw status 2>/dev/null | grep -q "active"; then
echo " Configuring ufw..."
for port in 3000 8001 8002 8003 8004 9000 9001 11434; do
sudo ufw allow "${port}/tcp" 2>/dev/null || true
done
echo " ✓ UFW ports opened"
fi
REMOTE_SCRIPT
echo ""
# -------------------------------------------------------
# Step 1: Clone or update the repo on the remote host
# -------------------------------------------------------
echo "--- Step 1: Syncing repository ---"
ssh "$REMOTE_HOST" bash -s -- "$REMOTE_DIR" "$REPO_URL" <<'REMOTE_SCRIPT'
set -euo pipefail
REMOTE_DIR="$1"
REPO_URL="$2"
if [ -d "$REMOTE_DIR/.git" ]; then
echo " Updating existing repo..."
cd "$REMOTE_DIR"
git fetch origin
git reset --hard origin/main
else
echo " Cloning fresh..."
git clone "$REPO_URL" "$REMOTE_DIR"
cd "$REMOTE_DIR"
fi
echo " ✓ Repo synced at $(git log --oneline -1)"
REMOTE_SCRIPT
echo ""
# -------------------------------------------------------
# Step 2: Detect or configure Ollama
# -------------------------------------------------------
echo "--- Step 2: Configuring Ollama ---"
# Always use the Docker Ollama container with GPU passthrough
# The ollama/ollama image ships with CUDA runtime built-in
USE_DOCKER_OLLAMA=true
OLLAMA_URL="http://ollama:11434"
echo " Using Docker Ollama container (GPU-accelerated via NVIDIA passthrough)"
echo " Host-accessible at localhost:11434"
echo ""
# -------------------------------------------------------
# Step 3: Create .env and compose override
# -------------------------------------------------------
echo "--- Step 3: Configuring environment ---"
ssh "$REMOTE_HOST" bash -s -- "$REMOTE_DIR" "$OLLAMA_URL" "$OLLAMA_MODEL" "$USE_DOCKER_OLLAMA" <<'REMOTE_SCRIPT'
set -euo pipefail
REMOTE_DIR="$1"
OLLAMA_URL="$2"
OLLAMA_MODEL="$3"
USE_DOCKER_OLLAMA="$4"
cd "$REMOTE_DIR"
# Read API keys from local files if they exist
POLYGON_KEY=""
ALPACA_KEY=""
ALPACA_SECRET=""
ALPACA_URL="https://paper-api.alpaca.markets"
[ -f polygon.io.key ] && POLYGON_KEY=$(cat polygon.io.key)
[ -f alpaca.key ] && ALPACA_KEY=$(cat alpaca.key)
[ -f alpaca.secret ] && ALPACA_SECRET=$(cat alpaca.secret)
[ -f alpaca.url ] && ALPACA_URL=$(cat alpaca.url)
cat > .env <<EOF
# Stonks Oracle — Docker Deployment Environment
MARKET_DATA_API_KEY=${POLYGON_KEY}
BROKER_API_KEY=${ALPACA_KEY}
BROKER_API_SECRET=${ALPACA_SECRET}
BROKER_BASE_URL=${ALPACA_URL}
TRADING_ENABLED=true
TRADING_RISK_TIER=moderate
TRADING_MAX_OPEN_POSITIONS=15
OLLAMA_MODEL=${OLLAMA_MODEL}
MACRO_ENABLED=true
COMPETITIVE_ENABLED=true
EOF
# Create compose override based on Ollama configuration
if [ "$USE_DOCKER_OLLAMA" = "true" ]; then
# Using Docker Ollama — no override needed, default compose handles it
rm -f docker-compose.override.yml
echo " ✓ Using Docker Ollama container"
else
# Using external Ollama — disable the container and point services to it
# Determine if URL is localhost (needs host-gateway) or remote
if echo "$OLLAMA_URL" | grep -qE "localhost|127\.0\.0\.1"; then
DOCKER_OLLAMA_URL="http://host.docker.internal:$(echo "$OLLAMA_URL" | grep -oP ':\K[0-9]+')"
cat > docker-compose.override.yml <<EOF
services:
ollama:
entrypoint: ["true"]
restart: "no"
ports: []
extractor:
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
environment:
OLLAMA_BASE_URL: "${DOCKER_OLLAMA_URL}"
extra_hosts:
- "host.docker.internal:host-gateway"
recommendation:
environment:
OLLAMA_BASE_URL: "${DOCKER_OLLAMA_URL}"
extra_hosts:
- "host.docker.internal:host-gateway"
EOF
else
# Remote Ollama — containers can reach it directly
cat > docker-compose.override.yml <<EOF
services:
ollama:
entrypoint: ["true"]
restart: "no"
extractor:
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
environment:
OLLAMA_BASE_URL: "${OLLAMA_URL}"
recommendation:
environment:
OLLAMA_BASE_URL: "${OLLAMA_URL}"
EOF
fi
echo " ✓ Override created — services will use external Ollama at ${OLLAMA_URL}"
fi
echo " ✓ .env configured (polygon=$([ -n "$POLYGON_KEY" ] && echo 'set' || echo 'empty'), alpaca=$([ -n "$ALPACA_KEY" ] && echo 'set' || echo 'empty'))"
REMOTE_SCRIPT
echo ""
# -------------------------------------------------------
# Step 4: Build and start all services
# -------------------------------------------------------
echo "--- Step 4: Building and starting services ---"
ssh "$REMOTE_HOST" bash -s -- "$REMOTE_DIR" "$USE_DOCKER_OLLAMA" <<'REMOTE_SCRIPT'
set -euo pipefail
REMOTE_DIR="$1"
USE_DOCKER_OLLAMA="$2"
cd "$REMOTE_DIR"
# Stop any existing deployment
docker compose down 2>/dev/null || true
# Build all images
echo " Building images (this may take a few minutes)..."
docker compose build --quiet 2>&1 | tail -5
# Start infrastructure
echo " Starting infrastructure..."
if [ "$USE_DOCKER_OLLAMA" = "true" ]; then
docker compose up -d postgres redis minio minio-init ollama
else
docker compose up -d postgres redis minio minio-init
fi
# Wait for infrastructure to be healthy
echo " Waiting for infrastructure health checks..."
for svc in postgres redis minio; do
for i in $(seq 1 30); do
if docker compose ps "$svc" 2>/dev/null | grep -q healthy; then
break
fi
sleep 2
done
done
echo " ✓ Infrastructure healthy"
# Start all application services
echo " Starting application services..."
docker compose up -d
echo " Waiting for services to stabilize..."
sleep 20
# Show status
echo ""
echo " Service Status:"
docker compose ps --format "table {{.Name}}\t{{.Status}}" 2>/dev/null | head -25 || docker compose ps
REMOTE_SCRIPT
echo ""
# -------------------------------------------------------
# Step 5: Seed the database
# -------------------------------------------------------
echo "--- Step 5: Seeding database ---"
ssh "$REMOTE_HOST" bash -s -- "$REMOTE_DIR" <<'REMOTE_SCRIPT'
set -euo pipefail
cd "$1"
# Wait for query-api to be healthy
for i in $(seq 1 30); do
if docker compose ps query-api 2>/dev/null | grep -q healthy; then
break
fi
sleep 3
done
# Run the symbol registry seed
echo " Seeding symbol registry..."
docker compose exec -T scheduler python -m services.symbol_registry.seed 2>/dev/null && echo " ✓ Database seeded" || echo " ⚠ Seed skipped (may already be seeded or service not ready)"
REMOTE_SCRIPT
echo ""
# -------------------------------------------------------
# Step 6: Ensure Ollama model is available
# -------------------------------------------------------
echo "--- Step 6: Checking Ollama model ---"
ssh "$REMOTE_HOST" bash -s -- "$OLLAMA_URL" "$OLLAMA_MODEL" "$USE_DOCKER_OLLAMA" "$REMOTE_DIR" <<'REMOTE_SCRIPT'
set -euo pipefail
OLLAMA_URL="$1"
OLLAMA_MODEL="$2"
USE_DOCKER_OLLAMA="$3"
REMOTE_DIR="$4"
if [ "$USE_DOCKER_OLLAMA" = "true" ]; then
# Pull via Docker container
cd "$REMOTE_DIR"
if docker compose exec -T ollama ollama list 2>/dev/null | grep -q "$OLLAMA_MODEL"; then
echo " ✓ Model $OLLAMA_MODEL already available"
else
echo " Pulling $OLLAMA_MODEL via Docker Ollama..."
docker compose exec -T ollama ollama pull "$OLLAMA_MODEL"
echo " ✓ Model pulled"
fi
else
# Check via API
if curl -sf "$OLLAMA_URL/api/tags" 2>/dev/null | grep -q "$OLLAMA_MODEL"; then
echo " ✓ Model $OLLAMA_MODEL already available at $OLLAMA_URL"
else
echo " Pulling $OLLAMA_MODEL via $OLLAMA_URL..."
curl -sf "$OLLAMA_URL/api/pull" -d "{\"name\":\"$OLLAMA_MODEL\"}" | tail -1
echo " ✓ Model pulled"
fi
fi
REMOTE_SCRIPT
echo ""
# -------------------------------------------------------
# Done
# -------------------------------------------------------
REMOTE_IP=$(echo "$REMOTE_HOST" | cut -d@ -f2)
echo "=== Deployment Complete ==="
echo ""
echo "Endpoints:"
echo " Dashboard: http://${REMOTE_IP}:3000"
echo " Query API: http://${REMOTE_IP}:8004"
echo " Symbol Registry: http://${REMOTE_IP}:8001"
echo " Trading Engine: http://${REMOTE_IP}:8002"
echo " Risk Engine: http://${REMOTE_IP}:8003"
echo " MinIO Console: http://${REMOTE_IP}:9001"
echo " Superset: http://${REMOTE_IP}:8088"
echo " Ollama: http://${REMOTE_IP}:11434"
echo ""
echo "Commands:"
echo " ssh $REMOTE_HOST 'cd $REMOTE_DIR && docker compose logs -f'"
echo " ssh $REMOTE_HOST 'cd $REMOTE_DIR && docker compose ps'"
echo " ssh $REMOTE_HOST 'cd $REMOTE_DIR && docker compose down'"
+311
View File
@@ -1,6 +1,21 @@
version: "3.9"
x-app-env: &app-env
POSTGRES_HOST: postgres
POSTGRES_PORT: "5432"
POSTGRES_DB: stonks
POSTGRES_USER: stonks
POSTGRES_PASSWORD: stonks_dev
REDIS_HOST: redis
REDIS_PORT: "6379"
MINIO_ENDPOINT: minio:9000
MINIO_ACCESS_KEY: minioadmin
MINIO_SECRET_KEY: minioadmin
OLLAMA_BASE_URL: http://ollama:11434
services:
# ── Infrastructure ──────────────────────────────────────────────
postgres:
image: postgres:16-alpine
environment:
@@ -67,6 +82,13 @@ services:
- "11434:11434"
volumes:
- ollama_models:/root/.ollama
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
trino:
image: trinodb/trino:latest
@@ -109,6 +131,295 @@ services:
depends_on:
- trino
# ── Application Services ────────────────────────────────────────
scheduler:
build:
context: .
dockerfile: docker/Dockerfile.scheduler
environment:
<<: *app-env
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "pgrep -f 'python -m services.scheduler.app' || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
symbol-registry:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000"
environment:
<<: *app-env
ports:
- "8001:8000"
depends_on:
postgres:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:8000/health || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
ingestion:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "python -m services.ingestion.worker"
environment:
<<: *app-env
env_file:
- .env
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
minio:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "pgrep -f 'python -m services.ingestion.worker' || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
parser:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "python -m services.parser.worker"
environment:
<<: *app-env
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "pgrep -f 'python -m services.parser.worker' || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
extractor:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "python -m services.extractor.main"
environment:
<<: *app-env
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
ollama:
condition: service_started
healthcheck:
test: ["CMD-SHELL", "pgrep -f 'python -m services.extractor.main' || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
aggregation:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "python -m services.aggregation.main"
environment:
<<: *app-env
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "pgrep -f 'python -m services.aggregation.main' || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
recommendation:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "python -m services.recommendation.main"
environment:
<<: *app-env
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "pgrep -f 'python -m services.recommendation.main' || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
trading-engine:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "uvicorn services.trading.app:app --host 0.0.0.0 --port 8000"
environment:
<<: *app-env
env_file:
- .env
ports:
- "8002:8000"
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:8000/health || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
risk-engine:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "uvicorn services.risk.app:app --host 0.0.0.0 --port 8000"
environment:
<<: *app-env
ports:
- "8003:8000"
networks:
default:
aliases:
- risk
depends_on:
postgres:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:8000/health || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
broker-adapter:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "python -m services.adapters.broker_service"
environment:
<<: *app-env
env_file:
- .env
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "pgrep -f 'python -m services.adapters.broker_service' || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
lake-publisher:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "python -m services.lake_publisher.jobs"
environment:
<<: *app-env
depends_on:
postgres:
condition: service_healthy
minio:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "pgrep -f 'python -m services.lake_publisher.jobs' || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
query-api:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "uvicorn services.api.app:app --host 0.0.0.0 --port 8000"
environment:
<<: *app-env
ports:
- "8004:8000"
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
minio:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:8000/health || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
restart: unless-stopped
dashboard:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "3000:8080"
depends_on:
query-api:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:8080/ || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 10s
restart: unless-stopped
volumes:
pgdata:
miniodata:
+618
View File
@@ -0,0 +1,618 @@
# AI Agent Building Guide
Stonks Oracle uses three AI agents powered by a local Ollama instance. Each agent has a dedicated purpose in the pipeline, a database-backed configuration, and support for A/B testing through variants. This guide covers how each agent works, how to configure them, how to create and test variants, and how to monitor performance.
## Table of Contents
- [Built-in Agents](#built-in-agents)
- [Document Intelligence Extractor](#1-document-intelligence-extractor)
- [Global Event Classifier](#2-global-event-classifier)
- [Thesis Rewriter](#3-thesis-rewriter)
- [Database Schema](#database-schema)
- [ai_agents Table](#ai_agents-table)
- [agent_variants Table](#agent_variants-table)
- [agent_performance_log Table](#agent_performance_log-table)
- [AgentConfigResolver](#agentconfigresolver)
- [Performance Logging and Variant Comparison](#performance-logging-and-variant-comparison)
- [API Endpoints](#api-endpoints)
- [Step-by-Step: Creating and Activating a Variant](#step-by-step-creating-and-activating-a-variant)
---
## Built-in Agents
Three agents are seeded into the `ai_agents` table on first migration (migration `026_ai_agents.sql`). They have `source = 'system'` and cannot be deleted through the API — only deactivated or edited.
### 1. Document Intelligence Extractor
| Field | Value |
|-------|-------|
| **Slug** | `document-extractor` |
| **Purpose** | Extracts structured intelligence (sentiment, catalysts, impact scores, key facts, risks) from company news, SEC filings, earnings transcripts, and press releases |
| **Default Model** | `qwen3.5:9b-fast` (Ollama) |
| **Prompt Version** | `document-intel-v2` |
| **Schema Version** | `2.0.0` |
| **Entry Point** | `services/extractor/main.py``services/extractor/client.py` |
**Input Data:**
- Normalized document text (fetched from MinIO or passed in the Redis job payload)
- Document type: `article`, `filing`, `transcript`, or `press_release`
- List of tracked tickers for company identification
- Document ID for traceability
**Output Schema** (`ExtractionResult`):
```json
{
"summary": "1-3 sentence summary",
"companies": [
{
"ticker": "AAPL",
"company_name": "Apple Inc.",
"relevance": 0.9,
"sentiment": "positive|negative|neutral|mixed",
"impact_score": 0.7,
"impact_horizon": "intraday|1d|1d_7d|1d_30d|30d_90d|90d_plus",
"catalyst_type": "earnings|product|legal|macro|supply_chain|m_and_a|rating_change|other",
"key_facts": ["fact1", "fact2"],
"risks": ["risk1"],
"evidence_spans": ["verbatim quote from document"]
}
],
"macro_themes": ["inflation", "ai_capex"],
"novelty_score": 0.6,
"confidence": 0.8,
"extraction_warnings": []
}
```
**System Prompt:**
```
You are a financial document analyst. Extract structured data as JSON.
Return ONLY a single JSON object. No markdown fences, no explanation,
no text before or after the JSON. Every field in the schema is required.
Use "other" for catalyst_type if unsure. Keep evidence_spans short
(under 20 words each). Keep key_facts to 3-5 items max.
```
**User Prompt Template** (built by `build_extraction_prompt()` in `services/extractor/prompts.py`):
- Includes document type and type-specific guidance (article, filing, transcript, press release)
- Includes tracked ticker list with rules for company identification
- Includes the full JSON schema field descriptions
- Truncates documents to 8,000 characters to limit inference time
---
### 2. Global Event Classifier
| Field | Value |
|-------|-------|
| **Slug** | `event-classifier` |
| **Purpose** | Classifies global/geopolitical news into structured macro events with impact type, severity, affected regions/sectors/commodities, and estimated duration |
| **Default Model** | `qwen3.5:9b-fast` (Ollama) |
| **Prompt Version** | `event-classification-v1` |
| **Schema Version** | `1.0.0` |
| **Entry Point** | `services/extractor/main.py``services/extractor/event_classifier.py` |
**Input Data:**
- Normalized text of a macro news article (from the `stonks:queue:macro_classification` Redis queue)
- Document ID for traceability
**Output Schema** (`GlobalEvent`):
```json
{
"event_types": ["trade_barrier", "commodity_shock"],
"severity": "low|moderate|high|critical",
"affected_regions": ["US", "CN"],
"affected_sectors": ["Energy", "Industrials"],
"affected_commodities": ["crude_oil"],
"summary": "1-3 sentence summary of event and market implications",
"key_facts": ["fact1", "fact2"],
"estimated_duration": "short_term|medium_term|long_term",
"confidence": 0.75
}
```
Valid `event_types`: `supply_disruption`, `demand_shift`, `cost_increase`, `regulatory_pressure`, `currency_impact`, `commodity_shock`, `trade_barrier`, `geopolitical_risk`
Valid `severity`: `low`, `moderate`, `high`, `critical`
**System Prompt:**
```
You classify MACRO-LEVEL global news into structured event JSON.
Return ONLY a single JSON object. No markdown, no explanation.
Every field is required. Keep key_facts to 3-5 items. Keep summary
under 3 sentences.
CRITICAL: Only classify articles about MACRO events that affect entire
markets, sectors, or economies. Examples: trade wars, interest rate
changes, commodity supply disruptions, regulatory changes, geopolitical
conflicts, natural disasters.
DO NOT classify as macro events: individual company earnings, lawsuits
against a single company, single-company management changes, individual
stock analysis, company-specific debt or bankruptcy, product launches
by one company. For these, set severity to "low", confidence below 0.3,
and leave affected_regions, affected_sectors, and affected_commodities
as empty arrays.
```
**User Prompt Template** (built by `build_event_classification_prompt()` in `services/extractor/event_classifier.py`):
- Includes anti-hallucination rules
- Lists all valid enum values for each field
- Truncates articles to 6,000 characters
---
### 3. Thesis Rewriter
| Field | Value |
|-------|-------|
| **Slug** | `thesis-rewriter` |
| **Purpose** | Rewrites deterministic trade thesis summaries into clear, professional analyst prose. Optional layer — the system falls back to the deterministic thesis if this fails |
| **Default Model** | `qwen3.5:9b-fast` (Ollama) |
| **Prompt Version** | `thesis-rewrite-v1` |
| **Schema Version** | `1.0.0` |
| **Entry Point** | `services/recommendation/main.py``services/recommendation/thesis_llm.py` |
**Input Data:**
- Deterministic thesis string (rule-based, built from trend data and eligibility rules)
- `TrendSummary` context: ticker, window, direction, strength, confidence, contradiction score, dominant catalysts, material risks
**Output Schema:**
- Plain text (not JSON). The model returns only the rewritten thesis as a string, under 150 words.
- On failure or empty response, the original deterministic thesis is returned unchanged.
**System Prompt:**
```
You are a concise financial analyst. You rewrite structured trade thesis
summaries into clear, professional prose suitable for an internal
research note.
STRICT RULES:
1. Do NOT add any information that is not present in the input.
2. Do NOT fabricate numbers, dates, company names, or analyst opinions.
3. Keep the rewrite under 150 words.
4. Preserve all factual claims, risk notes, and evidence counts from
the input.
5. Use a neutral, professional tone. Avoid hype or marketing language.
6. Return ONLY the rewritten thesis text. No JSON, no markdown, no
commentary.
```
**User Prompt Template** (built by `build_thesis_rewrite_prompt()` in `services/recommendation/thesis_llm.py`):
- Includes the deterministic thesis between delimiters
- Includes trend context: ticker, window, direction, strength, confidence, contradiction score, top catalysts, top risks
---
## Database Schema
### `ai_agents` Table
Defined in migration `026_ai_agents.sql`. Stores the base configuration for each agent.
| Column | Type | Default | Description |
|--------|------|---------|-------------|
| `id` | `UUID` | `gen_random_uuid()` | Primary key |
| `name` | `VARCHAR(100)` | — | Human-readable name (unique) |
| `slug` | `VARCHAR(100)` | — | URL-safe identifier (unique), used by `AgentConfigResolver` |
| `purpose` | `TEXT` | `''` | Description of what the agent does |
| `model_provider` | `VARCHAR(50)` | `'ollama'` | LLM provider |
| `model_name` | `VARCHAR(200)` | `'qwen3.5:9b'` | Model identifier |
| `system_prompt` | `TEXT` | `''` | System prompt sent to the model |
| `user_prompt_template` | `TEXT` | `''` | User prompt template (optional — code-defined templates take precedence) |
| `prompt_version` | `VARCHAR(100)` | `''` | Version tag for prompt tracking |
| `schema_version` | `VARCHAR(50)` | `'1.0.0'` | Version of the output schema |
| `temperature` | `FLOAT` | `0.0` | Model temperature |
| `max_tokens` | `INTEGER` | `32768` | Maximum output tokens |
| `timeout_seconds` | `INTEGER` | `120` | Request timeout |
| `max_retries` | `INTEGER` | `2` | Retry count on failure |
| `active` | `BOOLEAN` | `TRUE` | Whether the agent is enabled |
| `source` | `VARCHAR(20)` | `'system'` | `'system'` for built-in agents, `'user'` for API-created |
| `created_at` | `TIMESTAMPTZ` | `NOW()` | Creation timestamp |
| `updated_at` | `TIMESTAMPTZ` | `NOW()` | Last update timestamp |
**Indexes:**
- `idx_ai_agents_slug` on `slug`
- `idx_ai_agents_active` on `active`
**Registration:**
- **System-seeded**: The three built-in agents are inserted by migration 026 using `INSERT ... WHERE NOT EXISTS` — they are only created if no row with that slug exists. This means user edits to system agents are preserved across re-migrations.
- **API-created**: Users can create custom agents via `POST /api/agents`. These get `source = 'user'` and can be deleted.
### `agent_variants` Table
Defined in migration `027_agent_variants.sql`. Stores alternative configurations for A/B testing.
| Column | Type | Default | Description |
|--------|------|---------|-------------|
| `id` | `UUID` | `gen_random_uuid()` | Primary key |
| `agent_id` | `UUID` | — | Foreign key → `ai_agents(id)` (CASCADE delete) |
| `variant_name` | `VARCHAR(200)` | — | Human-readable variant name |
| `variant_slug` | `VARCHAR(200)` | — | URL-safe slug (unique per agent) |
| `description` | `TEXT` | `''` | What this variant changes |
| `model_provider` | `VARCHAR(50)` | `'ollama'` | LLM provider override |
| `model_name` | `VARCHAR(200)` | — | Model override |
| `system_prompt` | `TEXT` | `''` | System prompt override |
| `user_prompt_template` | `TEXT` | `''` | User prompt template override |
| `prompt_version` | `VARCHAR(100)` | `''` | Prompt version tag |
| `temperature` | `FLOAT` | `0.0` | Temperature override |
| `max_tokens` | `INTEGER` | `32768` | Max tokens override |
| `context_window` | `INTEGER` | `0` | Ollama `num_ctx` override (0 = model default) |
| `input_token_limit` | `INTEGER` | `0` | Max input tokens before truncation (0 = no limit) |
| `token_budget` | `INTEGER` | `0` | Total tokens per hour budget (0 = unlimited) |
| `timeout_seconds` | `INTEGER` | `120` | Timeout override |
| `max_retries` | `INTEGER` | `2` | Retry count override |
| `is_active` | `BOOLEAN` | `FALSE` | Whether this variant is the active override |
| `created_at` | `TIMESTAMPTZ` | `NOW()` | Creation timestamp |
| `updated_at` | `TIMESTAMPTZ` | `NOW()` | Last update timestamp |
**Indexes and Constraints:**
- `idx_agent_variants_slug` — unique index on `(agent_id, variant_slug)` — each agent's variant slugs must be unique
- `idx_agent_variants_active` — unique partial index on `(agent_id) WHERE is_active = TRUE`**at most one active variant per agent** (database-enforced)
- `idx_agent_variants_agent` — lookup by agent
### `agent_performance_log` Table
Defined in migration `026_ai_agents.sql`, extended in `027_agent_variants.sql` with `variant_id`.
| Column | Type | Default | Description |
|--------|------|---------|-------------|
| `id` | `UUID` | `gen_random_uuid()` | Primary key |
| `agent_id` | `UUID` | — | Foreign key → `ai_agents(id)` (CASCADE delete) |
| `variant_id` | `UUID` | `NULL` | Foreign key → `agent_variants(id)` (SET NULL on delete) |
| `document_id` | `UUID` | `NULL` | Foreign key → `documents(id)` (SET NULL on delete) |
| `ticker` | `VARCHAR(20)` | — | Stock ticker processed |
| `success` | `BOOLEAN` | — | Whether the invocation succeeded |
| `duration_ms` | `INTEGER` | `0` | Total invocation time in milliseconds |
| `confidence` | `FLOAT` | `0.0` | Model confidence score (0.0 for thesis rewrites) |
| `retry_count` | `INTEGER` | `0` | Number of retries before success/failure |
| `input_tokens` | `INTEGER` | `0` | Estimated input tokens (chars / 4) |
| `output_tokens` | `INTEGER` | `0` | Estimated output tokens (chars / 4) |
| `error_message` | `TEXT` | `NULL` | Error description on failure |
| `recorded_at` | `TIMESTAMPTZ` | `NOW()` | When the invocation occurred |
**Indexes:**
- `idx_agent_perf_agent` on `(agent_id, recorded_at DESC)`
- `idx_agent_perf_time` on `(recorded_at DESC)`
- `idx_agent_perf_variant` on `(variant_id, recorded_at DESC)`
---
## AgentConfigResolver
**Module:** `services/shared/agent_config.py`
The `AgentConfigResolver` is the central mechanism for resolving runtime agent configuration. All three agent services use it instead of duplicating resolution logic.
### How It Works
1. **Lookup by slug**: The resolver queries the `ai_agents` table by slug (e.g., `"document-extractor"`), joining with `agent_variants` to find any active variant.
2. **COALESCE-based override**: The SQL query uses `COALESCE(variant_column, agent_column)` for every configuration field. If an active variant exists and has a non-NULL value for a field, that value is used. Otherwise, the base agent's value is used.
```sql
SELECT a.id AS agent_id,
v.id AS variant_id,
COALESCE(v.model_provider, a.model_provider) AS model_provider,
COALESCE(v.model_name, a.model_name) AS model_name,
COALESCE(v.system_prompt, a.system_prompt) AS system_prompt,
COALESCE(v.user_prompt_template, a.user_prompt_template) AS user_prompt_template,
-- ... all other fields ...
FROM ai_agents a
LEFT JOIN agent_variants v
ON v.agent_id = a.id AND v.is_active = TRUE
WHERE a.slug = $1
AND a.active = TRUE
```
3. **TTL cache (60 seconds)**: Resolved configurations are cached in memory using `time.monotonic()`. Cache entries expire after 60 seconds (configurable via `ttl_seconds`). This means variant swaps take effect within 60 seconds without restarting any service.
4. **Fallback behavior**: If the database query fails or returns no rows (agent not found or inactive), the resolver returns `None`. Callers fall back to environment-variable-based `OllamaConfig` defaults.
### Resolved Config Dataclass
```python
@dataclass(frozen=True, slots=True)
class ResolvedAgentConfig:
agent_id: str
variant_id: str | None # None if no active variant
model_provider: str
model_name: str
system_prompt: str
user_prompt_template: str
prompt_version: str
temperature: float
max_tokens: int
context_window: int # Ollama num_ctx; 0 = model default
input_token_limit: int # Max input chars before truncation; 0 = no limit
token_budget: int # Hourly token budget; 0 = unlimited
timeout_seconds: int
max_retries: int
```
### Usage Pattern
```python
from services.shared.agent_config import AgentConfigResolver
resolver = AgentConfigResolver(pool, ttl_seconds=60)
config = await resolver.resolve("document-extractor")
if config is None:
# Fall back to env-var defaults
...
else:
# Use config.model_name, config.system_prompt, etc.
...
```
### Cache Invalidation
```python
resolver.invalidate("document-extractor") # Clear one entry
resolver.invalidate() # Clear all entries
```
### Config Refresh in Workers
The extractor and recommendation workers periodically re-resolve their agent config (every 100 jobs for the extractor, every 50 jobs for the recommendation worker). If the resolved model changes, the worker creates a new `OllamaClient` instance with the updated configuration.
---
## Performance Logging and Variant Comparison
Every agent invocation is logged to `agent_performance_log` with the `agent_id` and `variant_id` (if a variant was active). This enables comparing variant effectiveness.
### What Gets Logged
- **Document extractor**: Logged in `services/extractor/main.py` after each extraction. Records success/failure, duration, confidence, retry count, token estimates.
- **Event classifier**: Logged in `services/extractor/event_classifier.py` after each classification. Same fields.
- **Thesis rewriter**: Logged in `services/recommendation/thesis_llm.py` after each rewrite attempt. Confidence is always 0.0 (not applicable for rewrites).
### Querying for Variant Comparison
Compare two variants of the document extractor over the last 24 hours:
```sql
SELECT
v.variant_name,
COUNT(*) AS total_invocations,
COUNT(*) FILTER (WHERE p.success) AS successes,
ROUND(100.0 * COUNT(*) FILTER (WHERE p.success) / COUNT(*), 1) AS success_rate_pct,
ROUND(AVG(p.duration_ms)::numeric) AS avg_duration_ms,
ROUND(PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY p.duration_ms)::numeric) AS p95_duration_ms,
ROUND(AVG(p.confidence)::numeric, 4) AS avg_confidence,
ROUND(AVG(p.retry_count)::numeric, 2) AS avg_retries,
SUM(p.input_tokens + p.output_tokens) AS total_tokens
FROM agent_performance_log p
JOIN agent_variants v ON v.id = p.variant_id
WHERE p.agent_id = '<agent-uuid>'
AND p.recorded_at >= NOW() - INTERVAL '24 hours'
GROUP BY v.variant_name
ORDER BY success_rate_pct DESC;
```
Compare base agent (no variant) vs active variant:
```sql
SELECT
CASE WHEN p.variant_id IS NULL THEN 'base' ELSE v.variant_name END AS config,
COUNT(*) AS invocations,
ROUND(100.0 * COUNT(*) FILTER (WHERE p.success) / COUNT(*), 1) AS success_rate_pct,
ROUND(AVG(p.duration_ms)::numeric) AS avg_duration_ms,
ROUND(AVG(p.confidence)::numeric, 4) AS avg_confidence
FROM agent_performance_log p
LEFT JOIN agent_variants v ON v.id = p.variant_id
WHERE p.agent_id = '<agent-uuid>'
AND p.recorded_at >= NOW() - INTERVAL '48 hours'
GROUP BY config
ORDER BY config;
```
### Token Budget Enforcement
Variants can set a `token_budget` (total tokens per hour). Before each invocation, the worker checks:
```sql
SELECT COALESCE(SUM(input_tokens + output_tokens), 0) AS total_tokens
FROM agent_performance_log
WHERE variant_id = $1
AND recorded_at >= NOW() - INTERVAL '1 hour'
```
If the budget is exceeded, the invocation is skipped (extractor) or falls back to the deterministic thesis (thesis rewriter).
---
## API Endpoints
All agent endpoints are served by the Query API (`services/api/app.py`) under the `/api/agents` prefix.
### Agent CRUD
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/agents` | List all agents. Query param: `active_only` (bool, default `false`) |
| `GET` | `/api/agents/{agent_id}` | Get a single agent by UUID |
| `POST` | `/api/agents` | Create a new user-defined agent (returns 201) |
| `PUT` | `/api/agents/{agent_id}` | Partial update an agent (system or user) |
| `DELETE` | `/api/agents/{agent_id}` | Delete a user-created agent. Returns 403 for system agents |
**Create Agent Request Body:**
```json
{
"name": "My Custom Agent",
"slug": "my-custom-agent",
"purpose": "Custom extraction for earnings calls",
"model_provider": "ollama",
"model_name": "llama3.1:8b",
"system_prompt": "You are a financial analyst...",
"user_prompt_template": "",
"prompt_version": "v1",
"schema_version": "1.0.0",
"temperature": 0.0,
"max_tokens": 32768,
"timeout_seconds": 120,
"max_retries": 2
}
```
**Update Agent Request Body** (all fields optional):
```json
{
"model_name": "qwen3.5:14b",
"system_prompt": "Updated prompt...",
"temperature": 0.1,
"active": false
}
```
### Agent Performance
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/agents/{agent_id}/performance` | Aggregated metrics. Query param: `hours` (int, default 24, max 720) |
| `GET` | `/api/agents/{agent_id}/performance/history` | Hourly time-series. Query param: `hours` (int, default 24, max 720) |
**Performance Response:**
```json
{
"total_invocations": 1250,
"successes": 1180,
"failures": 70,
"avg_duration_ms": 3400,
"p95_duration_ms": 8200,
"avg_confidence": 0.7234,
"avg_retries": 0.15,
"total_input_tokens": 5000000,
"total_output_tokens": 1200000,
"success_rate": 0.944
}
```
### Variant CRUD
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/agents/{agent_id}/variants` | List all variants for an agent |
| `GET` | `/api/agents/{agent_id}/variants/{variant_id}` | Get a single variant |
| `POST` | `/api/agents/{agent_id}/variants` | Create a new variant (returns 201, 409 on duplicate slug) |
| `PUT` | `/api/agents/{agent_id}/variants/{variant_id}` | Partial update a variant |
| `DELETE` | `/api/agents/{agent_id}/variants/{variant_id}` | Delete a variant (returns 400 if active) |
### Clone Endpoints
| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/api/agents/{agent_id}/clone` | Clone an agent's base config as a new variant |
| `POST` | `/api/agents/{agent_id}/variants/{variant_id}/clone` | Clone an existing variant as a new variant |
Clone requests copy all configuration fields from the source, with optional overrides in the request body.
### Activate / Deactivate
| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/api/agents/{agent_id}/variants/{variant_id}/activate` | Set a variant as active (deactivates any other active variant in a single transaction) |
| `POST` | `/api/agents/{agent_id}/variants/deactivate` | Deactivate the currently active variant (agent falls back to base config) |
### Per-Variant Performance
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/agents/{agent_id}/variants/{variant_id}/performance` | Aggregated metrics for a specific variant |
| `GET` | `/api/agents/{agent_id}/variants/{variant_id}/performance/history` | Hourly time-series for a specific variant |
---
## Step-by-Step: Creating and Activating a Variant
This walkthrough creates a new variant of the document extractor that uses a different model and activates it for live traffic.
### 1. Find the Agent ID
```bash
curl -s https://stonks-api.celestium.life/api/agents?active_only=true | jq '.[] | select(.slug == "document-extractor") | .id'
```
Note the UUID — we'll call it `AGENT_ID`.
### 2. Clone the Agent as a Variant
```bash
curl -s -X POST https://stonks-api.celestium.life/api/agents/$AGENT_ID/clone \
-H "Content-Type: application/json" \
-d '{
"variant_name": "Llama 3.1 8B Test",
"description": "Testing llama3.1:8b as an alternative to qwen3.5:9b-fast",
"model_name": "llama3.1:8b",
"temperature": 0.1
}' | jq .
```
This creates a new variant with all fields copied from the base agent, except `model_name` and `temperature` which are overridden. The variant starts as `is_active: false`.
Note the variant's `id` — we'll call it `VARIANT_ID`.
### 3. Activate the Variant
```bash
curl -s -X POST \
https://stonks-api.celestium.life/api/agents/$AGENT_ID/variants/$VARIANT_ID/activate | jq .
```
This atomically deactivates any previously active variant and activates the new one. Within 60 seconds (the TTL cache window), the extractor worker will pick up the new configuration and start using `llama3.1:8b`.
### 4. Monitor Performance
Wait for some documents to be processed, then compare:
```bash
# Base agent performance (all invocations)
curl -s "https://stonks-api.celestium.life/api/agents/$AGENT_ID/performance?hours=4" | jq .
# Variant-specific performance
curl -s "https://stonks-api.celestium.life/api/agents/$AGENT_ID/variants/$VARIANT_ID/performance?hours=4" | jq .
```
Check the hourly trend:
```bash
curl -s "https://stonks-api.celestium.life/api/agents/$AGENT_ID/variants/$VARIANT_ID/performance/history?hours=12" | jq .
```
### 5. Roll Back (Deactivate)
If the variant underperforms, deactivate it to revert to the base agent config:
```bash
curl -s -X POST \
https://stonks-api.celestium.life/api/agents/$AGENT_ID/variants/deactivate | jq .
```
The extractor will revert to the base `qwen3.5:9b-fast` configuration within 60 seconds.
### 6. Iterate
You can update the variant's prompt or parameters without creating a new one:
```bash
curl -s -X PUT \
https://stonks-api.celestium.life/api/agents/$AGENT_ID/variants/$VARIANT_ID \
-H "Content-Type: application/json" \
-d '{
"system_prompt": "You are a financial document analyst. Extract structured data as JSON. Be extra conservative with impact scores — only assign > 0.7 for material events with concrete numbers.",
"prompt_version": "document-intel-v2-conservative"
}' | jq .
```
Then re-activate and compare again.
File diff suppressed because it is too large Load Diff
+274
View File
@@ -0,0 +1,274 @@
# Data Pipeline Architecture — Stonks Oracle
This document describes the end-to-end data pipeline from external data sources through signal processing to trade execution. The pipeline is queue-driven, with Redis lists connecting each stage and PostgreSQL/MinIO providing durable storage at every step.
All queue names follow the convention `stonks:queue:<name>` (see `services/shared/redis_keys.py`). Dead-letter queues mirror the pattern as `stonks:dlq:<name>`.
## Pipeline Overview
```mermaid
flowchart TB
%% ── External Data Sources ─────────────────────────────────────
subgraph sources ["External Data Sources"]
direction LR
polygon["Polygon.io<br/><i>News, Market Bars,<br/>Grouped Daily</i>"]
sec["SEC EDGAR<br/><i>10-K, 10-Q Filings</i>"]
macro_src["Macro News APIs<br/><i>Geopolitical &amp;<br/>Economic Events</i>"]
market_src["Market Data API<br/><i>Intraday Bars,<br/>Grouped Daily</i>"]
end
%% ── Scheduler ─────────────────────────────────────────────────
scheduler["<b>Scheduler</b><br/><i>services.scheduler.app</i><br/>Cadence polling, rate limiting,<br/>backoff &amp; stale recovery"]
sources -.->|"API polling<br/>on cadence"| scheduler
%% ── Ingestion Queue ───────────────────────────────────────────
q_ingestion[["stonks:queue:ingestion"]]
scheduler -->|"rpush job"| q_ingestion
%% ── Ingestion Worker ──────────────────────────────────────────
ingestion["<b>Ingestion</b><br/><i>services.ingestion.worker</i><br/>Adapter dispatch, dedupe,<br/>raw artifact upload"]
q_ingestion -->|"lpop"| ingestion
%% ── Raw Storage ───────────────────────────────────────────────
minio_raw[("MinIO<br/><i>Raw Artifacts</i><br/>JSON / HTML")]
pg_docs[("PostgreSQL<br/><i>documents,<br/>ingestion_runs</i>")]
redis_dedupe[("Redis<br/><i>Dedupe Markers</i><br/>stonks:dedupe:*")]
ingestion -->|"upload raw payload"| minio_raw
ingestion -->|"persist metadata"| pg_docs
ingestion -->|"set content hash"| redis_dedupe
%% ── Parsing Queue ─────────────────────────────────────────────
q_parsing[["stonks:queue:parsing"]]
ingestion -->|"rpush<br/>(news, filings,<br/>web_scrape)"| q_parsing
%% ── Parser Worker ─────────────────────────────────────────────
parser["<b>Parser</b><br/><i>services.parser.worker</i><br/>HTML parsing, quality scoring,<br/>company mention detection"]
q_parsing -->|"lpop"| parser
minio_norm[("MinIO<br/><i>Normalized Text</i><br/><i>Parser Output JSON</i>")]
parser -->|"upload normalized text"| minio_norm
parser -->|"update document status,<br/>insert mentions"| pg_docs
```
## Three Signal Layers
The parser routes documents into two extraction paths based on `document_type`. All three signal layers converge at the aggregation stage through the shared `WeightedSignal` abstraction.
```mermaid
flowchart TB
%% ── Parser Output ─────────────────────────────────────────────
parser(("Parser"))
%% ── Extraction Queues ─────────────────────────────────────────
q_extraction[["stonks:queue:extraction"]]
q_macro[["stonks:queue:macro_classification"]]
parser -->|"rpush<br/>(standard docs)"| q_extraction
parser -->|"rpush<br/>(macro_event docs)"| q_macro
%% ── Extractor Worker ──────────────────────────────────────────
subgraph extractor_svc ["Extractor Service"]
direction TB
ext_main["<b>Extractor</b><br/><i>services.extractor.main</i><br/>Alternates between queues<br/>(2 extraction : 1 macro)"]
end
q_extraction -->|"lpop"| ext_main
q_macro -->|"lpop"| ext_main
%% ── Ollama LLM ───────────────────────────────────────────────
ollama["<b>Ollama</b><br/><i>LLM Inference</i><br/>document-extractor agent<br/>event-classifier agent"]
ext_main <-->|"HTTP /api/generate"| ollama
%% ── Signal Layer 1: Company ───────────────────────────────────
subgraph layer1 ["Layer 1 — Company Signals"]
direction LR
di["document_intelligence<br/>document_impact_records"]
end
ext_main -->|"persist extraction<br/>(standard docs)"| di
%% ── Signal Layer 2: Macro ─────────────────────────────────────
subgraph layer2 ["Layer 2 — Macro Signals"]
direction LR
ge["global_events"]
mir["macro_impact_records<br/><i>per-company interpolation</i>"]
ge --> mir
end
ext_main -->|"classify &amp; persist<br/>(macro_event docs)"| ge
ext_main -->|"compute_macro_impact<br/>for all tracked companies"| mir
%% ── Aggregation Queue ─────────────────────────────────────────
q_agg[["stonks:queue:aggregation"]]
ext_main -->|"rpush<br/>(per ticker)"| q_agg
%% ── Aggregation Worker ────────────────────────────────────────
aggregation["<b>Aggregation</b><br/><i>services.aggregation.main</i><br/>Trend windows, scoring,<br/>contradiction detection"]
q_agg -->|"lpop"| aggregation
%% ── Signal Layer 3: Competitive ──────────────────────────────
subgraph layer3 ["Layer 3 — Competitive Signals"]
direction LR
pm["pattern_matcher<br/><i>historical patterns</i>"]
sp["signal_propagation<br/><i>cross-company signals</i>"]
csr["competitive_signal_records"]
pm --> sp --> csr
end
aggregation -->|"trigger_signal_propagation<br/>(when competitive_enabled)"| layer3
%% ── All layers merge ──────────────────────────────────────────
pg_trends[("PostgreSQL<br/><i>trend_windows,<br/>trend_history,<br/>trend_projections</i>")]
di -->|"WeightedSignal"| aggregation
mir -->|"WeightedSignal"| aggregation
csr -->|"WeightedSignal"| aggregation
aggregation -->|"persist trend summaries"| pg_trends
```
## Recommendation → Trading → Broker
```mermaid
flowchart TB
%% ── Recommendation Queue ──────────────────────────────────────
q_rec[["stonks:queue:recommendation"]]
aggregation(("Aggregation")) -->|"rpush<br/>(ticker + window,<br/>dedup 5 min TTL)"| q_rec
%% ── Recommendation Worker ─────────────────────────────────────
recommendation["<b>Recommendation</b><br/><i>services.recommendation.main</i><br/>Eligibility, suppression,<br/>thesis generation"]
q_rec -->|"lpop"| recommendation
ollama_thesis["<b>Ollama</b><br/><i>thesis-rewriter agent</i><br/>(optional LLM rewrite)"]
recommendation <-->|"rewrite thesis<br/>(trading-eligible only)"| ollama_thesis
pg_recs[("PostgreSQL<br/><i>recommendations,<br/>recommendation_evidence,<br/>risk_evaluations</i>")]
recommendation -->|"persist recommendation<br/>+ evidence + risk eval"| pg_recs
%% ── Trading Engine ────────────────────────────────────────────
subgraph trading_loop ["Trading Engine Decision Loop"]
direction TB
poll["Poll recommendations<br/><i>action IN (buy, sell)<br/>mode IN (paper, live)<br/>generated_at &gt; last_poll</i>"]
dedup_check["Redis dedup check<br/><i>stonks:dedupe:trading:*</i>"]
evaluate["evaluate_recommendation<br/><i>Circuit breaker check<br/>Trading window check<br/>Confidence gate<br/>Sector exposure check<br/>Correlation check<br/>Earnings blackout</i>"]
size["Position sizing<br/><i>Kelly criterion,<br/>risk tier limits</i>"]
decide{{"Decision"}}
poll --> dedup_check --> evaluate --> size --> decide
end
pg_recs -->|"SELECT recent<br/>recommendations"| poll
%% ── Broker Queue ──────────────────────────────────────────────
q_broker[["stonks:queue:broker_orders"]]
decide -->|"act → rpush<br/>order job"| q_broker
decide -->|"skip → persist<br/>decision only"| pg_decisions
pg_decisions[("PostgreSQL<br/><i>trading_decisions</i>")]
%% ── Broker Adapter ────────────────────────────────────────────
broker["<b>Broker Adapter</b><br/><i>services.adapters.broker_service</i><br/>Risk evaluation, idempotency,<br/>order submission, fill tracking"]
q_broker -->|"lpop"| broker
%% ── Risk Engine ───────────────────────────────────────────────
risk["<b>Risk Engine</b><br/><i>services.risk.app</i><br/>POST /evaluate<br/>Approval workflow"]
broker <-->|"evaluate order"| risk
%% ── Alpaca ────────────────────────────────────────────────────
alpaca["<b>Alpaca</b><br/><i>Paper Trading API</i><br/>Order submission,<br/>position sync"]
broker <-->|"submit order /<br/>sync positions"| alpaca
pg_orders[("PostgreSQL<br/><i>orders, order_events,<br/>positions,<br/>portfolio_snapshots</i>")]
broker -->|"persist order,<br/>events, positions"| pg_orders
%% ── Notifications ─────────────────────────────────────────────
subgraph notifications ["Notifications"]
direction LR
sns["AWS SNS<br/><i>SMS alerts</i>"]
gmail["Gmail SMTP<br/><i>Email alerts</i>"]
end
trading_loop -->|"circuit breaker trips,<br/>order fills,<br/>stop-loss triggers"| notifications
```
## Analytical Branch — Lake Publisher
The lake publisher runs as a separate worker, consuming from its own queue and writing partitioned Parquet fact tables to MinIO for analytical queries.
```mermaid
flowchart LR
%% ── Lake Publish Queue ────────────────────────────────────────
q_lake[["stonks:queue:lake_publish"]]
various(("Various Services<br/><i>ingestion, extractor,<br/>recommendation,<br/>broker adapter</i>"))
various -->|"enqueue_lake_job"| q_lake
%% ── Lake Publisher Worker ─────────────────────────────────────
lake["<b>Lake Publisher</b><br/><i>services.lake_publisher.jobs</i><br/>Transforms operational data<br/>into analytical facts"]
q_lake -->|"lpop"| lake
pg_source[("PostgreSQL<br/><i>Operational Tables</i><br/>documents, extractions,<br/>orders, positions, events")]
lake -->|"query source data"| pg_source
%% ── MinIO Parquet ─────────────────────────────────────────────
minio_lake[("MinIO<br/><i>Lakehouse Bucket</i><br/>Partitioned Parquet<br/>/year=/month=/day=")]
lake -->|"write Parquet files"| minio_lake
%% ── Trino ─────────────────────────────────────────────────────
trino["<b>Trino</b><br/><i>SQL Query Engine</i><br/>Hive connector → MinIO"]
minio_lake -->|"read via<br/>Hive Metastore"| trino
hive["<b>Hive Metastore</b><br/><i>Schema catalog</i>"]
trino <-->|"table metadata"| hive
hive -->|"location refs"| minio_lake
%% ── Visualization ─────────────────────────────────────────────
superset["<b>Superset</b><br/><i>Dashboards &amp;<br/>SQL Lab</i>"]
dashboard["<b>React Dashboard</b><br/><i>frontend</i><br/>Charts, portfolio,<br/>recommendations"]
query_api["<b>Query API</b><br/><i>services.api.app</i>"]
trino --> superset
trino --> query_api
query_api --> dashboard
```
## Complete Queue Topology
| Queue | Full Key | Producer(s) | Consumer |
|-------|----------|-------------|----------|
| Ingestion | `stonks:queue:ingestion` | Scheduler | Ingestion Worker |
| Parsing | `stonks:queue:parsing` | Ingestion Worker | Parser Worker |
| Extraction | `stonks:queue:extraction` | Parser (standard docs) | Extractor Worker |
| Macro Classification | `stonks:queue:macro_classification` | Parser (macro_event docs), Scheduler | Extractor Worker |
| Aggregation | `stonks:queue:aggregation` | Extractor Worker | Aggregation Worker |
| Recommendation | `stonks:queue:recommendation` | Aggregation Worker | Recommendation Worker |
| Broker Orders | `stonks:queue:broker_orders` | Trading Engine, Trading API (manual overrides) | Broker Adapter |
| Lake Publish | `stonks:queue:lake_publish` | Various services | Lake Publisher |
Dead-letter queues follow the pattern `stonks:dlq:<queue_name>` and are populated when a job exhausts its retry budget.
## Data Store Summary
| Store | Role | Key Tables / Buckets |
|-------|------|---------------------|
| **PostgreSQL** | Structured operational data | `documents`, `document_intelligence`, `document_impact_records`, `global_events`, `macro_impact_records`, `competitive_signal_records`, `trend_windows`, `trend_history`, `trend_projections`, `recommendations`, `recommendation_evidence`, `risk_evaluations`, `orders`, `order_events`, `positions`, `portfolio_snapshots`, `trading_decisions` |
| **Redis** | Queues, dedup markers, rate limits, circuit breaker state | `stonks:queue:*`, `stonks:dedupe:*`, `stonks:ratelimit:*`, `stonks:trading:circuit_breaker:*`, `stonks:dlq:*` |
| **MinIO** | Object storage for raw artifacts, normalized text, and analytical Parquet files | Raw artifacts bucket, normalized text bucket, lakehouse bucket (partitioned Parquet) |
## External Integration Points
| Integration | Service | Protocol | Purpose |
|-------------|---------|----------|---------|
| **Polygon.io** | Ingestion (via adapters) | HTTPS REST | News articles, market bars, grouped daily data |
| **SEC EDGAR** | Ingestion (via FilingsDataAdapter) | HTTPS REST | 10-K, 10-Q filings |
| **Ollama** | Extractor, Recommendation | HTTP `/api/generate` | LLM inference for document extraction, event classification, thesis rewriting |
| **Alpaca** | Broker Adapter | HTTPS REST | Paper trading order submission, position sync, account state |
| **AWS SNS** | Trading Engine (notifications) | boto3 SDK | SMS alerts for circuit breaker trips, order fills, stop-loss triggers |
| **Gmail** | Trading Engine (notifications) | SMTP (port 587 STARTTLS) | Email alerts for trading events |
| **Trino** | Query API, Superset | JDBC / HTTP | SQL queries over lakehouse Parquet files |
+322
View File
@@ -0,0 +1,322 @@
# Docker Compose Architecture — Stonks Oracle
This document describes the Docker Compose deployment topology for Stonks Oracle, derived from the `docker-compose.yml` file at the repository root.
All containers run on a single Docker network created by Compose. Infrastructure services (PostgreSQL, Redis, MinIO, Ollama, Trino, Hive Metastore, Superset) start first, and application services wait for their dependencies via `depends_on` with health check conditions.
## Container Topology Diagram
```mermaid
graph TB
%% ── Host machine ──────────────────────────────────────────────
host((Host Machine))
%% ── .env file ─────────────────────────────────────────────────
envfile[".env file<br/><i>MARKET_DATA_API_KEY</i><br/><i>BROKER_API_KEY</i><br/><i>BROKER_API_SECRET</i><br/><i>BROKER_BASE_URL</i>"]
%% ── Docker Compose default network ────────────────────────────
subgraph network ["Docker Compose Network (default)"]
direction TB
%% ── Infrastructure Containers ─────────────────────────────
subgraph infra ["Infrastructure Containers"]
direction LR
postgres[("postgres<br/><i>postgres:16-alpine</i><br/>host :5432 → :5432")]
redis[("redis<br/><i>redis:7-alpine</i><br/>host :6379 → :6379")]
minio[("minio<br/><i>minio/minio:latest</i><br/>host :9000 → :9000<br/>host :9001 → :9001")]
ollama[("ollama<br/><i>ollama/ollama:latest</i><br/>host :11434 → :11434")]
end
subgraph infra_init ["Infrastructure Init"]
minio_init["minio-init<br/><i>minio/mc:latest</i><br/><i>Creates buckets on startup</i>"]
end
subgraph analytics ["Analytics Containers"]
direction LR
hive_metastore["hive-metastore<br/><i>apache/hive:4.0.0</i><br/>host :9083 → :9083"]
trino["trino<br/><i>trinodb/trino:latest</i><br/>host :8080 → :8080"]
superset["superset<br/><i>apache/superset:latest</i><br/>host :8088 → :8088"]
end
%% ── Application Containers ────────────────────────────────
subgraph api_tier ["API Tier"]
direction LR
query_api["query-api<br/><i>docker/Dockerfile</i><br/><i>uvicorn services.api.app</i><br/>host :8004 → :8000"]
symbol_registry["symbol-registry<br/><i>docker/Dockerfile</i><br/><i>uvicorn services.symbol_registry.app</i><br/>host :8001 → :8000"]
end
subgraph frontend_tier ["Frontend Tier"]
dashboard["dashboard<br/><i>frontend/Dockerfile</i><br/><i>nginx on :8080</i><br/>host :3000 → :8080"]
end
subgraph trading_tier ["Trading Tier"]
direction LR
trading_engine["trading-engine<br/><i>docker/Dockerfile</i><br/><i>uvicorn services.trading.app</i><br/>host :8002 → :8000"]
risk_engine["risk-engine<br/><i>docker/Dockerfile</i><br/><i>uvicorn services.risk.app</i><br/>host :8003 → :8000"]
broker_adapter["broker-adapter<br/><i>docker/Dockerfile</i><br/><i>python -m services.adapters.broker_service</i><br/><i>no host port</i>"]
end
subgraph orchestration_tier ["Orchestration Tier"]
scheduler["scheduler<br/><i>docker/Dockerfile.scheduler</i><br/><i>no host port</i>"]
end
subgraph processing_tier ["Processing Tier (pipeline workers)"]
direction LR
ingestion["ingestion<br/><i>docker/Dockerfile</i><br/><i>python -m services.ingestion.worker</i><br/><i>no host port</i>"]
parser["parser<br/><i>docker/Dockerfile</i><br/><i>python -m services.parser.worker</i><br/><i>no host port</i>"]
extractor["extractor<br/><i>docker/Dockerfile</i><br/><i>python -m services.extractor.main</i><br/><i>no host port</i>"]
aggregation["aggregation<br/><i>docker/Dockerfile</i><br/><i>python -m services.aggregation.main</i><br/><i>no host port</i>"]
recommendation["recommendation<br/><i>docker/Dockerfile</i><br/><i>python -m services.recommendation.main</i><br/><i>no host port</i>"]
end
subgraph analytics_worker ["Analytics Worker"]
lake_publisher["lake-publisher<br/><i>docker/Dockerfile</i><br/><i>python -m services.lake_publisher.jobs</i><br/><i>no host port</i>"]
end
end
%% ── Host port access ──────────────────────────────────────────
host -->|":5432"| postgres
host -->|":6379"| redis
host -->|":9000 / :9001"| minio
host -->|":11434"| ollama
host -->|":8080"| trino
host -->|":9083"| hive_metastore
host -->|":8088"| superset
host -->|":8001"| symbol_registry
host -->|":8004"| query_api
host -->|":8002"| trading_engine
host -->|":8003"| risk_engine
host -->|":3000"| dashboard
%% ── .env injection ────────────────────────────────────────────
envfile -.->|"env_file: .env"| ingestion
envfile -.->|"env_file: .env"| broker_adapter
envfile -.->|"env_file: .env"| trading_engine
%% ── Styles ────────────────────────────────────────────────────
classDef infraSvc fill:#95a5a6,stroke:#717d7e,color:#fff
classDef analyticsSvc fill:#e74c3c,stroke:#a93226,color:#fff
classDef apiSvc fill:#4a90d9,stroke:#2c5f8a,color:#fff
classDef frontendSvc fill:#50c878,stroke:#2e7d46,color:#fff
classDef tradingSvc fill:#e8a838,stroke:#b07d1a,color:#fff
classDef orchSvc fill:#1abc9c,stroke:#148f77,color:#fff
classDef processSvc fill:#9b59b6,stroke:#6c3483,color:#fff
classDef initSvc fill:#bdc3c7,stroke:#7f8c8d,color:#333
classDef envSvc fill:#f5f5dc,stroke:#999,color:#333
class postgres,redis,minio,ollama infraSvc
class hive_metastore,trino,superset,lake_publisher analyticsSvc
class query_api,symbol_registry apiSvc
class dashboard frontendSvc
class trading_engine,risk_engine,broker_adapter tradingSvc
class scheduler orchSvc
class ingestion,parser,extractor,aggregation,recommendation processSvc
class minio_init initSvc
class envfile envSvc
```
## Dependency Graph
The following diagram shows `depends_on` relationships and health check conditions. Solid arrows indicate `condition: service_healthy` (the dependent waits for the health check to pass). Dashed arrows indicate `condition: service_started` (the dependent waits only for the container to start).
```mermaid
graph LR
%% ── Infrastructure health checks ──────────────────────────────
postgres[("postgres<br/><i>pg_isready -U stonks</i>")]
redis[("redis<br/><i>redis-cli ping</i>")]
minio[("minio<br/><i>mc ready local</i>")]
ollama[("ollama<br/><i>no health check</i>")]
%% ── Analytics dependencies ────────────────────────────────────
hive["hive-metastore"] -->|started| minio
trino["trino"] -->|started| minio
trino -->|started| hive
superset["superset"] -->|started| trino
minio_init["minio-init"] -->|healthy| minio
%% ── Application depends_on (healthy) ──────────────────────────
scheduler["scheduler"] -->|healthy| postgres
scheduler -->|healthy| redis
symbol_registry["symbol-registry"] -->|healthy| postgres
ingestion["ingestion"] -->|healthy| postgres
ingestion -->|healthy| redis
ingestion -->|healthy| minio
parser["parser"] -->|healthy| postgres
parser -->|healthy| redis
extractor["extractor"] -->|healthy| postgres
extractor -->|healthy| redis
extractor -.->|started| ollama
aggregation["aggregation"] -->|healthy| postgres
aggregation -->|healthy| redis
recommendation["recommendation"] -->|healthy| postgres
recommendation -->|healthy| redis
trading_engine["trading-engine"] -->|healthy| postgres
trading_engine -->|healthy| redis
risk_engine["risk-engine"] -->|healthy| postgres
broker_adapter["broker-adapter"] -->|healthy| postgres
broker_adapter -->|healthy| redis
lake_publisher["lake-publisher"] -->|healthy| postgres
lake_publisher -->|healthy| minio
query_api["query-api"] -->|healthy| postgres
query_api -->|healthy| redis
query_api -->|healthy| minio
dashboard["dashboard"] -->|healthy| query_api
%% ── Styles ────────────────────────────────────────────────────
classDef infraSvc fill:#95a5a6,stroke:#717d7e,color:#fff
classDef appSvc fill:#4a90d9,stroke:#2c5f8a,color:#fff
classDef analyticsSvc fill:#e74c3c,stroke:#a93226,color:#fff
classDef initSvc fill:#bdc3c7,stroke:#7f8c8d,color:#333
class postgres,redis,minio,ollama infraSvc
class scheduler,symbol_registry,ingestion,parser,extractor,aggregation,recommendation,trading_engine,risk_engine,broker_adapter,lake_publisher,query_api,dashboard appSvc
class hive,trino,superset analyticsSvc
class minio_init initSvc
```
## Named Volumes
Docker Compose defines five named volumes for persistent data:
```mermaid
graph LR
pgdata["📦 pgdata"]
miniodata["📦 miniodata"]
ollama_models["📦 ollama_models"]
hive_data["📦 hive_data"]
superset_data["📦 superset_data"]
pgdata -->|"/var/lib/postgresql/data"| postgres[("postgres")]
miniodata -->|"/data"| minio[("minio")]
ollama_models -->|"/root/.ollama"| ollama[("ollama")]
hive_data -->|"/opt/hive/data"| hive["hive-metastore"]
superset_data -->|"/app/superset_home"| superset["superset"]
classDef volStyle fill:#f5f5dc,stroke:#999,color:#333
classDef svcStyle fill:#95a5a6,stroke:#717d7e,color:#fff
class pgdata,miniodata,ollama_models,hive_data,superset_data volStyle
class postgres,minio,ollama,hive,superset svcStyle
```
| Volume | Mount Point | Container | Purpose |
|--------|-------------|-----------|---------|
| `pgdata` | `/var/lib/postgresql/data` | postgres | PostgreSQL database files |
| `miniodata` | `/data` | minio | MinIO object storage data |
| `ollama_models` | `/root/.ollama` | ollama | Downloaded LLM model weights |
| `hive_data` | `/opt/hive/data` | hive-metastore | Hive Metastore embedded Derby DB |
| `superset_data` | `/app/superset_home` | superset | Superset configuration and metadata |
### Bind Mounts
In addition to named volumes, several containers use bind mounts for configuration files:
| Host Path | Mount Point | Container | Mode |
|-----------|-------------|-----------|------|
| `./infra/migrations/` | `/docker-entrypoint-initdb.d` | postgres | rw (init scripts) |
| `./infra/trino/catalog/` | `/etc/trino/catalog` | trino | rw |
| `./infra/hive/core-site.xml` | `/opt/hive/conf/core-site.xml` | hive-metastore | ro |
| `./infra/hive/metastore-site.xml` | `/opt/hive/conf/metastore-site.xml` | hive-metastore | ro |
## Host Port Mappings
Services accessible from the host machine:
| Host Port | Container | Container Port | Service |
|-----------|-----------|----------------|---------|
| 5432 | postgres | 5432 | PostgreSQL database |
| 6379 | redis | 6379 | Redis cache and queues |
| 9000 | minio | 9000 | MinIO S3 API |
| 9001 | minio | 9001 | MinIO web console |
| 11434 | ollama | 11434 | Ollama LLM API |
| 8080 | trino | 8080 | Trino query engine |
| 9083 | hive-metastore | 9083 | Hive Metastore thrift |
| 8088 | superset | 8088 | Superset dashboard |
| 8001 | symbol-registry | 8000 | Symbol Registry API |
| 8002 | trading-engine | 8000 | Trading Engine API |
| 8003 | risk-engine | 8000 | Risk Engine API |
| 8004 | query-api | 8000 | Query API |
| 3000 | dashboard | 8080 | React dashboard (nginx) |
Services without host port mappings (internal only): scheduler, ingestion, parser, extractor, aggregation, recommendation, broker-adapter, lake-publisher, minio-init.
## Environment Configuration
### Shared Environment (`x-app-env` YAML anchor)
All 13 application services and the scheduler receive these environment variables via the `x-app-env` anchor:
| Variable | Value | Purpose |
|----------|-------|---------|
| `POSTGRES_HOST` | `postgres` | Docker Compose service name for PostgreSQL |
| `POSTGRES_PORT` | `5432` | PostgreSQL port |
| `POSTGRES_DB` | `stonks` | Database name |
| `POSTGRES_USER` | `stonks` | Database user |
| `POSTGRES_PASSWORD` | `stonks_dev` | Database password (dev default) |
| `REDIS_HOST` | `redis` | Docker Compose service name for Redis |
| `REDIS_PORT` | `6379` | Redis port |
| `MINIO_ENDPOINT` | `minio:9000` | Docker Compose service name for MinIO |
| `MINIO_ACCESS_KEY` | `minioadmin` | MinIO access key |
| `MINIO_SECRET_KEY` | `minioadmin` | MinIO secret key |
| `OLLAMA_BASE_URL` | `http://ollama:11434` | Docker Compose service name for Ollama |
### `.env` File (API Keys)
Three services load additional secrets from the `.env` file in the repository root via `env_file: .env`:
| Variable | Required By | Purpose |
|----------|-------------|---------|
| `MARKET_DATA_API_KEY` | ingestion | Polygon.io market data API key |
| `BROKER_API_KEY` | broker-adapter, trading-engine | Alpaca broker API key |
| `BROKER_API_SECRET` | broker-adapter, trading-engine | Alpaca broker API secret |
| `BROKER_BASE_URL` | broker-adapter, trading-engine | Alpaca API base URL (default: `https://paper-api.alpaca.markets`) |
## Health Check Summary
| Container | Health Check Command | Interval | Timeout | Retries | Start Period |
|-----------|---------------------|----------|---------|---------|--------------|
| postgres | `pg_isready -U stonks` | 5s | — | 5 | — |
| redis | `redis-cli ping` | 5s | — | 5 | — |
| minio | `mc ready local` | 5s | — | 5 | — |
| symbol-registry | `curl -f http://localhost:8000/health` | 10s | 5s | 3 | 15s |
| query-api | `curl -f http://localhost:8000/health` | 10s | 5s | 3 | 15s |
| trading-engine | `curl -f http://localhost:8000/health` | 10s | 5s | 3 | 15s |
| risk-engine | `curl -f http://localhost:8000/health` | 10s | 5s | 3 | 15s |
| dashboard | `curl -f http://localhost:8080/` | 10s | 5s | 3 | 10s |
| scheduler | `pgrep -f 'python -m services.scheduler.app'` | 10s | 5s | 3 | 15s |
| ingestion | `pgrep -f 'python -m services.ingestion.worker'` | 10s | 5s | 3 | 15s |
| parser | `pgrep -f 'python -m services.parser.worker'` | 10s | 5s | 3 | 15s |
| extractor | `pgrep -f 'python -m services.extractor.main'` | 10s | 5s | 3 | 15s |
| aggregation | `pgrep -f 'python -m services.aggregation.main'` | 10s | 5s | 3 | 15s |
| recommendation | `pgrep -f 'python -m services.recommendation.main'` | 10s | 5s | 3 | 15s |
| broker-adapter | `pgrep -f 'python -m services.adapters.broker_service'` | 10s | 5s | 3 | 15s |
| lake-publisher | `pgrep -f 'python -m services.lake_publisher.jobs'` | 10s | 5s | 3 | 15s |
Infrastructure services (ollama, trino, hive-metastore, superset) do not define health checks in docker-compose.yml. Application services that depend on ollama use `condition: service_started` instead of `condition: service_healthy`.
## Internal Network Connectivity
All containers share the default Docker Compose network. Services reference each other by their Compose service name as the hostname:
| Hostname | Resolved To | Used By |
|----------|-------------|---------|
| `postgres` | PostgreSQL container | All 13 app services, superset |
| `redis` | Redis container | scheduler, ingestion, parser, extractor, aggregation, recommendation, trading-engine, broker-adapter, query-api |
| `minio` | MinIO container | ingestion, lake-publisher, query-api (via `minio:9000`) |
| `ollama` | Ollama container | extractor (via `http://ollama:11434`) |
| `hive-metastore` | Hive Metastore container | trino (thrift://hive-metastore:9083) |
| `trino` | Trino container | superset (trino:8080) |
| `query-api` | Query API container | dashboard (nginx proxy upstream) |
+355
View File
@@ -0,0 +1,355 @@
# Kubernetes Architecture — Stonks Oracle
This document describes the Kubernetes deployment topology for Stonks Oracle, derived from the Helm chart at `infra/helm/stonks-oracle/`.
All application workloads deploy to the `stonks-oracle` namespace. External cluster services (PostgreSQL, Redis, MinIO, Ollama) run in their own namespaces and are referenced via cross-namespace DNS.
## Deployment Diagram
```mermaid
graph TB
%% ── External traffic ──────────────────────────────────────────
internet((Internet))
subgraph traefik ["kube-system (Traefik Ingress Controller)"]
direction LR
ing_dash["stonks.celestium.life"]
ing_api["stonks-api.celestium.life"]
ing_reg["stonks-registry.celestium.life"]
ing_trade["stonks-trading.celestium.life"]
ing_superset["stonks-dash.celestium.life"]
ing_trino["stonks-trino.celestium.life"]
end
internet --> traefik
%% ── stonks-oracle namespace ───────────────────────────────────
subgraph ns ["stonks-oracle namespace"]
direction TB
%% ── API Tier (ingress-facing) ─────────────────────────────
subgraph api_tier ["API Tier"]
direction LR
query_api["query-api<br/><i>Deployment (1 replica)</i><br/>:8000"]
symbol_registry["symbol-registry<br/><i>Deployment (1 replica)</i><br/>:8000"]
end
%% ── Frontend Tier ─────────────────────────────────────────
subgraph frontend_tier ["Frontend Tier"]
dashboard["dashboard<br/><i>Deployment (1 replica)</i><br/>:8080<br/><i>nginx-unprivileged</i>"]
end
%% ── Trading Tier ──────────────────────────────────────────
subgraph trading_tier ["Trading Tier"]
direction LR
trading_engine["trading-engine<br/><i>Deployment (1 replica)</i><br/>:8000"]
risk_engine["risk-engine<br/><i>Deployment (1 replica)</i><br/>:8000"]
broker_adapter["broker-adapter<br/><i>Deployment (1 replica)</i><br/><i>queue-driven worker</i>"]
end
%% ── Orchestration Tier ────────────────────────────────────
subgraph orchestration_tier ["Orchestration Tier"]
scheduler["scheduler<br/><i>Deployment (1 replica)</i><br/><i>runs migrations + seed</i>"]
end
%% ── Processing Tier (pipeline workers) ────────────────────
subgraph processing_tier ["Processing Tier (pipeline workers)"]
direction LR
ingestion["ingestion<br/><i>Deployment (2 replicas)</i>"]
parser["parser<br/><i>Deployment (2 replicas)</i>"]
extractor["extractor<br/><i>Deployment (1 replica)</i>"]
aggregation["aggregation<br/><i>Deployment (4 replicas)</i>"]
recommendation["recommendation<br/><i>Deployment (1 replica)</i>"]
end
%% ── Analytics Tier ────────────────────────────────────────
subgraph analytics_tier ["Analytics Tier"]
direction LR
lake_publisher["lake-publisher<br/><i>Deployment (1 replica)</i><br/><i>queue-driven worker</i>"]
hive_metastore["hive-metastore<br/><i>Deployment (1 replica)</i><br/>:9083<br/><i>apache/hive:4.0.0</i>"]
trino["trino<br/><i>Deployment (1 replica)</i><br/>:8080<br/><i>trinodb/trino:latest</i>"]
superset["superset<br/><i>Deployment (1 replica)</i><br/>:8088<br/><i>custom image</i>"]
end
%% ── Helm Secrets ──────────────────────────────────────────
subgraph secrets_block ["Helm-Managed Secrets"]
direction LR
sec_core["stonks-core-secrets<br/><i>POSTGRES_PASSWORD</i><br/><i>MINIO_ACCESS_KEY</i><br/><i>MINIO_SECRET_KEY</i><br/><i>REDIS_PASSWORD</i>"]
sec_broker["stonks-broker-secrets<br/><i>BROKER_API_KEY</i><br/><i>BROKER_API_SECRET</i><br/><i>BROKER_BASE_URL</i>"]
sec_market["stonks-market-secrets<br/><i>MARKET_DATA_API_KEY</i>"]
sec_gmail["stonks-gmail-secrets<br/><i>GMAIL_SENDER</i><br/><i>GMAIL_RECIPIENT</i><br/><i>GMAIL_APP_PASSWORD</i>"]
sec_dashboard["stonks-dashboard-secrets<br/><i>SUPERSET_SECRET_KEY</i><br/><i>SUPERSET_ADMIN_PASSWORD</i>"]
end
%% ── ConfigMap ─────────────────────────────────────────────
configmap["stonks-config<br/><i>ConfigMap</i><br/><i>All env vars from values.yaml config block</i>"]
end
%% ── External Cluster Services ─────────────────────────────────
subgraph pg_ns ["postgresql-service namespace"]
postgres[("PostgreSQL<br/>postgresql-rw:5432")]
end
subgraph redis_ns ["redis-service namespace"]
redis[("Redis<br/>redis-master:6379")]
end
subgraph minio_ns ["minio-service namespace"]
minio[("MinIO<br/>minio:80")]
end
subgraph ollama_ns ["ollama-service namespace"]
ollama[("Ollama<br/>ollama:11434<br/><i>GPU: 4070 Ti Super</i>")]
end
%% ── Ingress Routes ────────────────────────────────────────────
ing_dash -->|":8080"| dashboard
ing_api -->|":8000"| query_api
ing_reg -->|":8000"| symbol_registry
ing_trade -->|":8000"| trading_engine
ing_superset -->|":8088"| superset
ing_trino -->|":8080"| trino
%% ── Dashboard → Backend APIs ──────────────────────────────────
dashboard -.->|"/api/ proxy"| query_api
dashboard -.->|"/registry/ proxy"| symbol_registry
dashboard -.->|"/risk/ proxy"| risk_engine
%% ── Pipeline data flow (via Redis queues) ─────────────────────
scheduler -->|"enqueue jobs"| redis
ingestion -->|"stonks:queue:parsing"| redis
parser -->|"stonks:queue:extraction"| redis
extractor -->|"stonks:queue:aggregation"| redis
aggregation -->|"stonks:queue:recommendation"| redis
recommendation -->|"stonks:queue:trading_decisions"| redis
trading_engine -->|"stonks:queue:broker_orders"| redis
broker_adapter -->|"read orders"| redis
lake_publisher -->|"stonks:queue:lake_publish"| redis
%% ── External service connections ──────────────────────────────
scheduler --> postgres
scheduler --> redis
ingestion --> postgres
ingestion --> redis
ingestion --> minio
parser --> postgres
parser --> redis
extractor --> postgres
extractor --> redis
extractor --> ollama
aggregation --> postgres
aggregation --> redis
recommendation --> postgres
recommendation --> redis
trading_engine --> postgres
trading_engine --> redis
risk_engine --> postgres
broker_adapter --> postgres
broker_adapter --> redis
lake_publisher --> postgres
lake_publisher --> minio
query_api --> postgres
query_api --> redis
query_api --> minio
symbol_registry --> postgres
%% ── Analytics plane connections ───────────────────────────────
lake_publisher -->|"Parquet → s3a://stonks-lakehouse"| minio
hive_metastore -->|"s3a:// catalog"| minio
trino -->|"thrift://hive-metastore:9083"| hive_metastore
superset -->|"trino:8080"| trino
query_api -->|"trino:8080"| trino
superset --> postgres
superset --> redis
%% ── Trading tier external egress ──────────────────────────────
trading_engine -->|"HTTPS :443<br/>Alpaca API"| internet
trading_engine -->|"SMTP :587<br/>Gmail notifications"| internet
broker_adapter -->|"HTTPS :443<br/>Alpaca API"| internet
ingestion -->|"HTTPS :443<br/>Polygon.io / News APIs"| internet
%% ── Secret consumption ────────────────────────────────────────
sec_core -.-> query_api
sec_core -.-> symbol_registry
sec_core -.-> scheduler
sec_core -.-> ingestion
sec_core -.-> parser
sec_core -.-> extractor
sec_core -.-> aggregation
sec_core -.-> recommendation
sec_core -.-> trading_engine
sec_core -.-> risk_engine
sec_core -.-> broker_adapter
sec_core -.-> lake_publisher
sec_core -.-> hive_metastore
sec_core -.-> trino
sec_core -.-> superset
sec_broker -.-> ingestion
sec_broker -.-> trading_engine
sec_broker -.-> risk_engine
sec_broker -.-> broker_adapter
sec_market -.-> ingestion
sec_gmail -.-> trading_engine
sec_dashboard -.-> superset
configmap -.-> query_api
configmap -.-> symbol_registry
configmap -.-> scheduler
configmap -.-> ingestion
configmap -.-> parser
configmap -.-> extractor
configmap -.-> aggregation
configmap -.-> recommendation
configmap -.-> trading_engine
configmap -.-> risk_engine
configmap -.-> broker_adapter
configmap -.-> lake_publisher
configmap -.-> superset
%% ── Styles ────────────────────────────────────────────────────
classDef apiSvc fill:#4a90d9,stroke:#2c5f8a,color:#fff
classDef frontendSvc fill:#50c878,stroke:#2e7d46,color:#fff
classDef tradingSvc fill:#e8a838,stroke:#b07d1a,color:#fff
classDef processSvc fill:#9b59b6,stroke:#6c3483,color:#fff
classDef orchSvc fill:#1abc9c,stroke:#148f77,color:#fff
classDef analyticsSvc fill:#e74c3c,stroke:#a93226,color:#fff
classDef extSvc fill:#95a5a6,stroke:#717d7e,color:#fff
classDef secretSvc fill:#f5f5dc,stroke:#999,color:#333
classDef configSvc fill:#dfe6e9,stroke:#999,color:#333
class query_api,symbol_registry apiSvc
class dashboard frontendSvc
class trading_engine,risk_engine,broker_adapter tradingSvc
class scheduler orchSvc
class ingestion,parser,extractor,aggregation,recommendation processSvc
class lake_publisher,hive_metastore,trino,superset analyticsSvc
class postgres,redis,minio,ollama extSvc
class sec_core,sec_broker,sec_market,sec_gmail,sec_dashboard secretSvc
class configmap configSvc
```
## Network Policy Boundaries
The Helm chart deploys a **default-deny-ingress** policy that blocks all inbound traffic to pods in the `stonks-oracle` namespace. Each service that needs inbound connections has an explicit allow policy:
```mermaid
graph LR
subgraph netpol ["Network Policies — stonks-oracle namespace"]
direction TB
deny["🔒 default-deny-ingress<br/><i>Blocks ALL ingress to all pods</i>"]
subgraph allows ["Explicit Allow Rules"]
direction TB
np_dash["allow-dashboard-ingress<br/>dashboard :8080<br/>← kube-system (Traefik)"]
np_api["allow-query-api-ingress<br/>query-api :8000<br/>← kube-system (Traefik)<br/>← dashboard pod"]
np_reg["allow-symbol-registry-ingress<br/>symbol-registry :8000<br/>← kube-system (Traefik)<br/>← dashboard pod"]
np_trade["allow-trading-engine-ingress<br/>trading-engine :8000<br/>← kube-system (Traefik)<br/>← query-api pod<br/>← dashboard pod<br/><i>Egress: PostgreSQL :5432,</i><br/><i>Redis :6379, HTTPS :443, SMTP :587</i>"]
np_risk["allow-risk-engine-ingress<br/>risk-engine :8000<br/>← broker-adapter pod<br/>← query-api pod<br/>← dashboard pod"]
np_superset["allow-superset-ingress<br/>superset :8088<br/>← kube-system (Traefik)"]
np_trino["allow-trino-ingress<br/>trino :8080<br/>← superset pod<br/>← query-api pod<br/>← kube-system (Traefik)"]
np_hive["allow-hive-metastore-ingress<br/>hive-metastore :9083<br/>← trino pod<br/>← lake-publisher pod"]
np_broker["deny-broker-adapter-ingress<br/>broker-adapter<br/><i>No inbound traffic allowed</i>"]
end
end
style deny fill:#e74c3c,stroke:#c0392b,color:#fff
style np_broker fill:#e74c3c,stroke:#c0392b,color:#fff
style np_dash fill:#2ecc71,stroke:#27ae60,color:#fff
style np_api fill:#2ecc71,stroke:#27ae60,color:#fff
style np_reg fill:#2ecc71,stroke:#27ae60,color:#fff
style np_trade fill:#f39c12,stroke:#d68910,color:#fff
style np_risk fill:#f39c12,stroke:#d68910,color:#fff
style np_superset fill:#2ecc71,stroke:#27ae60,color:#fff
style np_trino fill:#2ecc71,stroke:#27ae60,color:#fff
style np_hive fill:#3498db,stroke:#2980b9,color:#fff
```
### Services Without Ingress Policies (Pipeline Workers)
The following services have **no inbound network policy** — they are queue-driven workers that only make outbound connections to PostgreSQL, Redis, MinIO, and Ollama. The default-deny-ingress policy blocks any unsolicited inbound traffic:
| Service | Tier | Behavior |
|---------|------|----------|
| scheduler | orchestration | Polls DB, enqueues to Redis |
| ingestion | processing | Reads from `stonks:queue:ingestion`, writes to DB/MinIO/Redis |
| parser | processing | Reads from `stonks:queue:parsing`, writes to DB/Redis |
| extractor | processing | Reads from `stonks:queue:extraction`, calls Ollama, writes to DB/Redis |
| aggregation | processing | Reads from `stonks:queue:aggregation`, writes to DB/Redis |
| recommendation | processing | Reads from `stonks:queue:recommendation`, writes to DB/Redis |
| lake-publisher | analytics | Reads from `stonks:queue:lake_publish`, writes Parquet to MinIO |
## Service Tier Summary
| Tier | Services | Ingress? | Replicas | Notes |
|------|----------|----------|----------|-------|
| **api** | query-api, symbol-registry | Yes (Traefik) | 1 each | FastAPI, readiness probes on `/docs` |
| **frontend** | dashboard | Yes (Traefik) | 1 | nginx-unprivileged on :8080, proxies to API services |
| **trading** | trading-engine, risk-engine, broker-adapter | trading-engine: Yes; risk-engine: internal only; broker-adapter: denied | 1 each | trading-engine has egress to Alpaca + Gmail |
| **orchestration** | scheduler | No | 1 | Runs DB migrations + seed as init containers |
| **processing** | ingestion, parser, extractor, aggregation, recommendation | No | 2, 2, 1, 4, 1 | Pipeline-gated by `pipelineEnabled` toggle |
| **analytics** | lake-publisher, trino, hive-metastore, superset | trino + superset: Yes; others: No | 1 each | lake-publisher is pipeline-gated |
## Secret Consumption Map
| Secret | Keys | Consumers |
|--------|------|-----------|
| `stonks-core-secrets` | POSTGRES_PASSWORD, MINIO_ACCESS_KEY, MINIO_SECRET_KEY, REDIS_PASSWORD | All 13 app services + hive-metastore, trino, superset |
| `stonks-broker-secrets` | BROKER_API_KEY, BROKER_API_SECRET, BROKER_BASE_URL | ingestion, trading-engine, risk-engine, broker-adapter |
| `stonks-market-secrets` | MARKET_DATA_API_KEY | ingestion |
| `stonks-gmail-secrets` | GMAIL_SENDER, GMAIL_RECIPIENT, GMAIL_APP_PASSWORD | trading-engine |
| `stonks-dashboard-secrets` | SUPERSET_SECRET_KEY, SUPERSET_ADMIN_PASSWORD | superset |
## Pipeline Toggle
Setting `pipelineEnabled: false` in `values.yaml` scales all services with `pipeline: true` to 0 replicas. This affects:
- scheduler, ingestion, parser, extractor, aggregation, recommendation, broker-adapter, lake-publisher
API-tier services (query-api, symbol-registry), trading-tier services (trading-engine, risk-engine), analytics services (trino, hive-metastore, superset), and the dashboard always run regardless of this toggle.
## External Cluster Services
These services run outside the `stonks-oracle` namespace and are referenced via cross-namespace DNS:
| Service | Namespace | DNS | Port | Notes |
|---------|-----------|-----|------|-------|
| PostgreSQL | `postgresql-service` | `postgresql-rw.postgresql-service.svc.cluster.local` | 5432 | CloudNativePG managed |
| Redis | `redis-service` | `redis-master.redis-service.svc.cluster.local` | 6379 | Password in `stonks-core-secrets` |
| MinIO | `minio-service` | `minio.minio-service.svc.cluster.local` | 80 | S3-compatible object store |
| Ollama | `ollama-service` | `ollama.ollama-service.svc.cluster.local` | 11434 | LLM inference, GPU: 4070 Ti Super 16GB |
## Analytics Plane
The analytics stack runs within the `stonks-oracle` namespace:
1. **Lake Publisher** writes Parquet fact tables to MinIO at `s3a://stonks-lakehouse/warehouse`
2. **Hive Metastore** (Apache Hive 4.0.0) manages table metadata, backed by embedded Derby DB with a PVC for persistence. Connects to MinIO for S3A filesystem access.
3. **Trino** queries the lakehouse via Hive Metastore (thrift://hive-metastore:9083). Exposes two catalogs: `lakehouse` (Hive connector) and `iceberg` (Iceberg connector). Both connect to MinIO for data access.
4. **Superset** connects to Trino for lakehouse queries and to PostgreSQL for its metadata DB. Uses Redis for caching. Exposed externally via Traefik ingress.
## Ingress Routes
All ingress resources use the `traefik` IngressClass with TLS certificates issued by the `ca-issuer` ClusterIssuer:
| Domain | Backend Service | Port | TLS Secret |
|--------|----------------|------|------------|
| `stonks.celestium.life` | dashboard | 8080 | `stonks-dashboard-tls` |
| `stonks-api.celestium.life` | query-api | 8000 | `stonks-api-tls` |
| `stonks-registry.celestium.life` | symbol-registry | 8000 | `stonks-registry-tls` |
| `stonks-trading.celestium.life` | trading-engine | 8000 | `stonks-trading-tls` |
| `stonks-dash.celestium.life` | superset | 8088 | `stonks-dash-tls` |
| `stonks-trino.celestium.life` | trino | 8080 | `stonks-trino-tls` |
+440
View File
@@ -0,0 +1,440 @@
# Backup and Restore Guide
This guide documents every backup and restore script in the Stonks Oracle platform, their CLI options, storage locations, retention policies, and procedures for disaster recovery.
## Overview
Stonks Oracle provides two tiers of backup tooling:
| Tier | Scripts | Scope | Storage |
|------|---------|-------|---------|
| **Local (kubectl-based)** | `backup-db.sh`, `restore-db.sh`, `backup-redis.sh` | Individual data stores, streamed to the operator's machine | `~/backups/stonks-oracle/` (local filesystem) |
| **Cluster (Kubernetes Job)** | `backup.sh`, `restore.sh` | Full platform (PostgreSQL + all MinIO buckets) | NFS share at `192.168.42.8:/volume1/Kubernetes/stonks` |
All scripts live in the `scripts/` directory and require `kubectl` access to the cluster.
---
## Local Backup Scripts
### `backup-db.sh` — PostgreSQL Database Backup
Creates a compressed `pg_dump` of the `stonks` database and optionally uploads it to MinIO.
**Usage:**
```bash
./scripts/backup-db.sh # backup to local file
./scripts/backup-db.sh --upload-minio # backup + upload to MinIO
```
**CLI Arguments:**
| Argument | Required | Description |
|----------|----------|-------------|
| `--upload-minio` | No | Upload the backup file to the `stonks-backups` MinIO bucket after creating it |
**Environment Variables:**
| Variable | Default | Description |
|----------|---------|-------------|
| `BACKUP_DIR` | `~/backups/stonks-oracle` | Local directory where backup files are stored |
**What it captures:**
- Full `pg_dump` of the `stonks` database (all tables, data, sequences)
- Dump flags: `--no-owner --no-privileges --clean --if-exists`
- Output format: gzip-compressed SQL (`.sql.gz`)
**How it works:**
1. Runs `pg_dump` inside the PostgreSQL pod (`postgresql-1` in `postgresql-service` namespace) and streams the compressed output to the local machine
2. Validates the backup is non-empty and counts tables as a sanity check
3. If `--upload-minio` is specified, attempts to create the `stonks-backups` bucket (if it doesn't exist) and stages the file for upload
4. Prunes old backups, keeping only the last 7 files matching `stonks-*.sql.gz`
**Storage:**
- Local path: `~/backups/stonks-oracle/stonks-<YYYYMMDD-HHMMSS>.sql.gz`
- MinIO bucket (optional): `stonks-backups`
**Retention:** Keeps the last 7 backups. Older files matching `stonks-*.sql.gz` in the backup directory are automatically deleted.
---
### `backup-redis.sh` — Redis State Backup
Triggers a Redis `BGSAVE` and copies the RDB dump file to the local machine.
**Usage:**
```bash
./scripts/backup-redis.sh
```
**CLI Arguments:** None.
**Environment Variables:**
| Variable | Default | Description |
|----------|---------|-------------|
| `BACKUP_DIR` | `~/backups/stonks-oracle` | Local directory where the RDB file is stored |
| `REDIS_PASSWORD` | `PSCh4ng3me!` | Redis authentication password |
**What it captures:**
- Redis RDB snapshot (`dump.rdb`) containing all in-memory state: deduplication markers, queue contents, rate-limit counters, cached values
**How it works:**
1. Triggers `BGSAVE` on the Redis master pod (`redis-master-0` in `redis-service` namespace)
2. Waits 5 seconds for the background save to complete, then logs the `LASTSAVE` timestamp
3. Copies the RDB file from the pod. Tries `/data/dump.rdb` first, then falls back to `/var/lib/redis/dump.rdb` and `/bitnami/redis/data/dump.rdb`
4. Prints Redis keyspace statistics for verification
**Storage:**
- Local path: `~/backups/stonks-oracle/redis-<YYYYMMDD-HHMMSS>.rdb`
**Retention:** No automatic pruning. Old Redis backups accumulate and must be cleaned up manually.
---
### `restore-db.sh` — PostgreSQL Database Restore
Restores a `pg_dump` backup into the `stonks` database with full service scale-down/scale-up.
**Usage:**
```bash
./scripts/restore-db.sh <backup-file.sql.gz>
./scripts/restore-db.sh ~/backups/stonks-oracle/stonks-20260415-180000.sql.gz
```
If called without arguments, lists available backups in `~/backups/stonks-oracle/`.
**CLI Arguments:**
| Argument | Required | Description |
|----------|----------|-------------|
| `<backup-file.sql.gz>` | Yes | Path to the gzip-compressed SQL backup file to restore |
**What it restores:**
- All tables, data, sequences, and indexes in the `stonks` database
- Re-grants `ALL PRIVILEGES` to the `stonks` user on all tables and sequences after restore
**Service scale-down/scale-up procedure:**
1. **Terminates active connections** — Runs `pg_terminate_backend()` for all connections to the `stonks` database
2. **Scales down all deployments** in the `stonks-oracle` namespace to 0 replicas to prevent reconnections
3. **Waits 10 seconds** for pods to terminate
4. **Restores the backup** using `psql --single-transaction` (piped from `zcat`)
5. **Re-grants permissions** to the `stonks` user
6. **Verifies** the restore by counting tables
7. **Scales all deployments back to 1 replica**, then scales `ingestion` and `parser` to 2 replicas
**Data loss implications:**
> **WARNING:** This replaces ALL data in the `stonks` database with the backup contents. Any data written after the backup was taken is permanently lost. The script requires interactive confirmation — you must type `yes` to proceed.
---
## Cluster Backup Scripts (Kubernetes Jobs)
### `backup.sh` — Full Platform Backup (PostgreSQL + MinIO)
Runs a Kubernetes Job that backs up both PostgreSQL and all MinIO buckets to an NFS share.
**Usage:**
```bash
bash scripts/backup.sh
```
**CLI Arguments:** None.
**What it captures:**
- **PostgreSQL**: Full `pg_dump` in custom format (`-Fc`) as `stonks.pgdump`
- **MinIO buckets** (8 buckets mirrored):
- `stonks-raw-market` — Raw market data from Polygon.io
- `stonks-raw-news` — Raw news articles
- `stonks-raw-filings` — Raw SEC filings
- `stonks-normalized` — Normalized documents
- `stonks-llm-prompts` — LLM prompt logs
- `stonks-llm-results` — LLM extraction results
- `stonks-lakehouse` — Parquet fact tables for Trino
- `stonks-audit` — Audit trail artifacts
- **Manifest**: `manifest.json` with backup name, timestamp, and bucket list
**How it works:**
1. Deletes any previous `stonks-backup` Job
2. Creates a Kubernetes Job using `postgres:18-alpine` with NFS volume mount and MinIO credentials from cluster secrets
3. Inside the Job container:
- Runs `pg_dump` with credentials from `stonks-config` ConfigMap and `stonks-core-secrets` Secret
- Installs the MinIO client (`mc`) and mirrors each bucket to the NFS backup directory
- Writes a `manifest.json` and updates the `latest` symlink
4. Waits up to 600 seconds (10 minutes) for the Job to complete
5. Job auto-cleans after 300 seconds (`ttlSecondsAfterFinished`)
**Storage:**
- NFS path: `192.168.42.8:/volume1/Kubernetes/stonks/<backup-name>/`
- Directory structure:
```
stonks-backup-YYYYMMDD-HHMMSS/
├── stonks.pgdump # PostgreSQL custom-format dump
├── manifest.json # Backup metadata
└── minio/
├── stonks-raw-market/ # Mirrored bucket contents
├── stonks-raw-news/
├── stonks-raw-filings/
├── stonks-normalized/
├── stonks-llm-prompts/
├── stonks-llm-results/
├── stonks-lakehouse/
└── stonks-audit/
```
- A `latest` symlink always points to the most recent backup
**Retention:** No automatic pruning on NFS. Old backups must be cleaned up manually.
---
### `restore.sh` — Full Platform Restore (PostgreSQL + MinIO)
Runs a Kubernetes Job that restores both PostgreSQL and MinIO buckets from an NFS backup.
**Usage:**
```bash
bash scripts/restore.sh # restore from "latest" symlink
bash scripts/restore.sh <backup-name> # restore a specific backup
```
**CLI Arguments:**
| Argument | Required | Description |
|----------|----------|-------------|
| `<backup-name>` | No | Name of the backup directory on NFS. Defaults to `latest` (symlink to most recent backup) |
**What it restores:**
- **PostgreSQL**: Full database restore using `pg_restore --clean --if-exists --no-owner --no-acl`
- **MinIO buckets**: All 8 buckets mirrored back with `mc mirror --overwrite`
**How it works:**
1. Prints a warning and gives 5 seconds to abort (Ctrl+C)
2. Deletes any previous `stonks-restore` Job
3. Creates a Kubernetes Job that:
- Validates the backup exists (`stonks.pgdump` file present)
- Restores PostgreSQL using `pg_restore` with `--clean` (drops and recreates objects)
- Installs `mc` and mirrors each bucket back from NFS to MinIO
- Verifies the restore by querying row counts for key tables (companies, documents, intelligence, impacts, trends, recommendations)
4. Waits up to 600 seconds for the Job to complete
**Data loss implications:**
> **WARNING:** This will DROP and recreate all objects in the `stonks` database. All MinIO bucket contents are overwritten. Any data written after the backup was taken is permanently lost. The script provides a 5-second abort window before proceeding.
**Post-restore steps:**
After the restore completes, restart all services to pick up the restored state:
```bash
kubectl rollout restart deployment -n stonks-oracle --all
```
---
## MinIO Upload Option (`--upload-minio`)
The `backup-db.sh` script supports `--upload-minio` for off-host storage of database backups. When enabled:
1. The script connects to MinIO through an ingestion pod in the `stonks-oracle` namespace
2. Creates the `stonks-backups` bucket if it doesn't already exist
3. Stages the backup file for upload
This provides a second copy of the database backup on object storage, separate from the operator's local filesystem. The full cluster backup (`backup.sh`) stores backups on NFS and does not use this flag — it backs up MinIO bucket *contents* rather than uploading database dumps *to* MinIO.
---
## Full Nuke and Rebuild Procedure
When a complete platform reset is needed (corrupted state, major schema changes, fresh start), follow this procedure:
### Step 1: Tear Down Services
```bash
bash ~/sources/kube/stonks-oracle/runmelast.sh
```
This runs from `gremlin-1` and performs a Helm uninstall, cleaning up all Kubernetes resources in the `stonks-oracle` namespace. Database, MinIO, and Redis data are preserved (they run in separate namespaces).
### Step 2: Terminate Database Connections
```bash
kubectl exec -n postgresql-service postgresql-1 -c postgres -- \
psql -U postgres -c \
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'stonks' AND pid <> pg_backend_pid();"
```
### Step 3: Drop the Database
```bash
kubectl exec -n postgresql-service postgresql-1 -c postgres -- \
psql -U postgres -c "DROP DATABASE IF EXISTS stonks;"
```
### Step 4: Flush Redis
Clear all `stonks:*` keys to reset deduplication markers, queue contents, and cached state:
```bash
kubectl exec -n redis-service redis-master-0 -- \
redis-cli -a 'PSCh4ng3me!' --scan --pattern 'stonks:*' | \
xargs -L 100 kubectl exec -n redis-service redis-master-0 -- \
redis-cli -a 'PSCh4ng3me!' DEL
```
### Step 5: Redeploy
```bash
bash ~/sources/kube/stonks-oracle/runmefirst.sh
```
This runs from `gremlin-1` and performs:
- Database creation and migration (all `infra/migrations/*.sql` files applied in order)
- Helm install with secrets injected via `--set` flags
- Rolling restart of all deployments
### Step 6: Re-seed the Symbol Registry
```bash
POSTGRES_HOST=postgresql-rw.postgresql-service.svc.cluster.local \
POSTGRES_PASSWORD='St0nks0racl3!' \
POSTGRES_USER=stonks \
POSTGRES_DB=stonks \
.venv/bin/python -m services.symbol_registry.seed
```
This populates the 50 tracked companies across 10 sectors and 46 competitor relationships.
---
## Recommended Backup Schedules
### Daily Database Backup (cron)
Run `backup-db.sh` daily on a machine with `kubectl` access. The built-in retention keeps the last 7 backups automatically.
```cron
# Daily database backup at 2:00 AM
0 2 * * * /path/to/stonks-oracle/scripts/backup-db.sh --upload-minio >> /var/log/stonks-backup.log 2>&1
```
### Weekly Full Backup (cron)
Run the full cluster backup weekly to capture both PostgreSQL and MinIO data on NFS:
```cron
# Weekly full backup (PostgreSQL + MinIO) on Sundays at 3:00 AM
0 3 * * 0 /path/to/stonks-oracle/scripts/backup.sh >> /var/log/stonks-full-backup.log 2>&1
```
### Redis Backup Before Deployments
Redis state is transient (queues, dedup markers, caches) and rebuilds naturally. Back up Redis before major deployments or database resets as a precaution:
```bash
./scripts/backup-redis.sh
```
### Kubernetes CronJobs
For fully automated in-cluster backups, create a CronJob based on the same Job spec used by `backup.sh`:
```yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: stonks-backup
namespace: stonks-oracle
spec:
schedule: "0 2 * * *" # Daily at 2:00 AM UTC
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
ttlSecondsAfterFinished: 3600
backoffLimit: 1
template:
spec:
restartPolicy: Never
volumes:
- name: nfs-backup
nfs:
server: 192.168.42.8
path: /volume1/Kubernetes/stonks
containers:
- name: backup
image: postgres:18-alpine
volumeMounts:
- name: nfs-backup
mountPath: /backup
envFrom:
- configMapRef:
name: stonks-config
- secretRef:
name: stonks-core-secrets
env:
- name: MINIO_ACCESS_KEY
valueFrom:
secretKeyRef:
name: stonks-core-secrets
key: MINIO_ACCESS_KEY
- name: MINIO_SECRET_KEY
valueFrom:
secretKeyRef:
name: stonks-core-secrets
key: MINIO_SECRET_KEY
command: ["sh", "-c"]
args:
- |
set -e
apk add --no-cache curl ca-certificates
STAMP="stonks-backup-$(date +%Y%m%d-%H%M%S)"
DIR="/backup/${STAMP}"
mkdir -p "${DIR}/minio"
# PostgreSQL backup
PGPASSWORD="${POSTGRES_PASSWORD}" pg_dump \
-h "${POSTGRES_HOST}" -p "${POSTGRES_PORT}" \
-U "${POSTGRES_USER}" -d "${POSTGRES_DB}" \
--no-owner --no-acl -Fc \
-f "${DIR}/stonks.pgdump"
# MinIO backup
curl -sL https://dl.min.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc
chmod +x /usr/local/bin/mc
mc alias set backup "http://${MINIO_ENDPOINT}" "${MINIO_ACCESS_KEY}" "${MINIO_SECRET_KEY}" --api S3v4
for bucket in stonks-raw-market stonks-raw-news stonks-raw-filings stonks-normalized stonks-llm-prompts stonks-llm-results stonks-lakehouse stonks-audit; do
mc mirror "backup/${bucket}" "${DIR}/minio/${bucket}/" 2>/dev/null || true
done
ln -sfn "${STAMP}" /backup/latest
echo "Backup complete: ${DIR}"
```
### Recommended Schedule Summary
| What | Frequency | Script | Retention |
|------|-----------|--------|-----------|
| Database only | Daily | `backup-db.sh --upload-minio` | Last 7 (auto-pruned) |
| Full platform (DB + MinIO) | Weekly | `backup.sh` | Manual cleanup on NFS |
| Redis snapshot | Before deployments | `backup-redis.sh` | Manual cleanup |
+745
View File
@@ -0,0 +1,745 @@
# Docker Deployment Guide
This guide covers running the full Stonks Oracle platform locally using Docker Compose. It documents every service, environment variable, volume mount, health check, and operational command.
## Prerequisites
- Docker Engine 24+ and Docker Compose v2
- At least 16 GB RAM (Ollama + Trino + all services)
- API keys for Polygon.io and Alpaca (optional — platform runs in degraded mode without them)
## Quick Start
```bash
# 1. Clone the repository
git clone <repo-url> && cd stonks-oracle
# 2. Configure API keys
cp .env.example .env # or edit the existing .env
# Fill in MARKET_DATA_API_KEY, BROKER_API_KEY, BROKER_API_SECRET
# 3. Start everything
docker compose up -d
# 4. Verify all services are healthy
docker compose ps
# 5. Access the dashboard
open http://localhost:3000
```
---
## Service Inventory
### Infrastructure Services
| Service | Image | Ports | Volumes | Purpose |
|---------|-------|-------|---------|---------|
| `postgres` | `postgres:16-alpine` | `5432:5432` | `pgdata``/var/lib/postgresql/data`, `./infra/migrations``/docker-entrypoint-initdb.d` | Primary database; migrations auto-applied on first start |
| `redis` | `redis:7-alpine` | `6379:6379` | — | Queue broker, caching, deduplication |
| `minio` | `minio/minio:latest` | `9000:9000` (API), `9001:9001` (console) | `miniodata``/data` | Object storage for raw artifacts and lakehouse |
| `minio-init` | `minio/mc:latest` | — | — | One-shot init container that creates required buckets |
| `ollama` | `ollama/ollama:latest` | `11434:11434` | `ollama_models``/root/.ollama` | LLM inference server for extraction and classification |
| `trino` | `trinodb/trino:latest` | `8080:8080` | `./infra/trino/catalog``/etc/trino/catalog` | SQL query engine over the lakehouse |
| `hive-metastore` | `apache/hive:4.0.0` | `9083:9083` | `hive_data``/opt/hive/data`, `./infra/hive/core-site.xml``/opt/hive/conf/core-site.xml`, `./infra/hive/metastore-site.xml``/opt/hive/conf/metastore-site.xml` | Iceberg/Hive metadata catalog for Trino |
| `superset` | `apache/superset:latest` | `8088:8088` | `superset_data``/app/superset_home` | BI dashboards over Trino |
### Application Services
| Service | Dockerfile | `SERVICE_CMD` / Command | Ports | Depends On |
|---------|-----------|------------------------|-------|------------|
| `scheduler` | `docker/Dockerfile.scheduler` | `python -m services.scheduler.app` | — | postgres (healthy), redis (healthy) |
| `symbol-registry` | `docker/Dockerfile` | `uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000` | `8001:8000` | postgres (healthy) |
| `ingestion` | `docker/Dockerfile` | `python -m services.ingestion.worker` | — | postgres (healthy), redis (healthy), minio (healthy) |
| `parser` | `docker/Dockerfile` | `python -m services.parser.worker` | — | postgres (healthy), redis (healthy) |
| `extractor` | `docker/Dockerfile` | `python -m services.extractor.main` | — | postgres (healthy), redis (healthy), ollama (started) |
| `aggregation` | `docker/Dockerfile` | `python -m services.aggregation.main` | — | postgres (healthy), redis (healthy) |
| `recommendation` | `docker/Dockerfile` | `python -m services.recommendation.main` | — | postgres (healthy), redis (healthy) |
| `trading-engine` | `docker/Dockerfile` | `uvicorn services.trading.app:app --host 0.0.0.0 --port 8000` | `8002:8000` | postgres (healthy), redis (healthy) |
| `risk-engine` | `docker/Dockerfile` | `uvicorn services.risk.app:app --host 0.0.0.0 --port 8000` | `8003:8000` | postgres (healthy) |
| `broker-adapter` | `docker/Dockerfile` | `python -m services.adapters.broker_service` | — | postgres (healthy), redis (healthy) |
| `lake-publisher` | `docker/Dockerfile` | `python -m services.lake_publisher.jobs` | — | postgres (healthy), minio (healthy) |
| `query-api` | `docker/Dockerfile` | `uvicorn services.api.app:app --host 0.0.0.0 --port 8000` | `8004:8000` | postgres (healthy), redis (healthy), minio (healthy) |
| `dashboard` | `frontend/Dockerfile` | nginx (built-in) | `3000:8080` | query-api (healthy) |
### Port Summary
| Port | Service | Protocol |
|------|---------|----------|
| 3000 | Dashboard (React UI) | HTTP |
| 5432 | PostgreSQL | TCP |
| 6379 | Redis | TCP |
| 8001 | Symbol Registry API | HTTP |
| 8002 | Trading Engine API | HTTP |
| 8003 | Risk Engine API | HTTP |
| 8004 | Query API | HTTP |
| 8080 | Trino | HTTP |
| 8088 | Superset | HTTP |
| 9000 | MinIO API | HTTP |
| 9001 | MinIO Console | HTTP |
| 9083 | Hive Metastore | Thrift |
| 11434 | Ollama | HTTP |
---
## Environment Variables
### Shared Application Environment (`x-app-env`)
All application services inherit these variables via the `x-app-env` YAML anchor:
| Variable | Default | Description |
|----------|---------|-------------|
| `POSTGRES_HOST` | `postgres` | PostgreSQL hostname (Docker service name) |
| `POSTGRES_PORT` | `5432` | PostgreSQL port |
| `POSTGRES_DB` | `stonks` | Database name |
| `POSTGRES_USER` | `stonks` | Database user |
| `POSTGRES_PASSWORD` | `stonks_dev` | Database password |
| `REDIS_HOST` | `redis` | Redis hostname (Docker service name) |
| `REDIS_PORT` | `6379` | Redis port |
| `MINIO_ENDPOINT` | `minio:9000` | MinIO API endpoint |
| `MINIO_ACCESS_KEY` | `minioadmin` | MinIO access key |
| `MINIO_SECRET_KEY` | `minioadmin` | MinIO secret key |
| `OLLAMA_BASE_URL` | `http://ollama:11434` | Ollama LLM server URL |
### `.env` File
The `.env` file is loaded by `ingestion`, `broker-adapter`, and `trading-engine` via the `env_file` directive. Create it in the repository root:
```dotenv
# Stonks Oracle — Environment Variables
# These are loaded by ingestion, broker-adapter, and trading-engine services.
# Polygon.io market data API key (required for live data ingestion)
MARKET_DATA_API_KEY=
# Alpaca broker credentials (required for paper/live trading)
BROKER_API_KEY=
BROKER_API_SECRET=
BROKER_BASE_URL=https://paper-api.alpaca.markets
```
| Variable | Required | Default | Used By | Description |
|----------|----------|---------|---------|-------------|
| `MARKET_DATA_API_KEY` | No* | (empty) | ingestion | Polygon.io API key for market data fetching |
| `BROKER_API_KEY` | No* | (empty) | broker-adapter, trading-engine | Alpaca API key |
| `BROKER_API_SECRET` | No* | (empty) | broker-adapter, trading-engine | Alpaca API secret |
| `BROKER_BASE_URL` | No | `https://paper-api.alpaca.markets` | broker-adapter, trading-engine | Alpaca API base URL |
*Services start without these keys but run in degraded mode — ingestion cannot fetch market data and the broker adapter cannot execute trades.
### Infrastructure Service Environment
**PostgreSQL** (`postgres`):
| Variable | Value | Description |
|----------|-------|-------------|
| `POSTGRES_DB` | `stonks` | Database created on first start |
| `POSTGRES_USER` | `stonks` | Superuser for the database |
| `POSTGRES_PASSWORD` | `stonks_dev` | Password for the database user |
**MinIO** (`minio`):
| Variable | Value | Description |
|----------|-------|-------------|
| `MINIO_ROOT_USER` | `minioadmin` | MinIO admin username |
| `MINIO_ROOT_PASSWORD` | `minioadmin` | MinIO admin password |
**Trino** (`trino`):
| Variable | Value | Description |
|----------|-------|-------------|
| `MINIO_ACCESS_KEY` | `minioadmin` | Passed to Trino for MinIO catalog access |
| `MINIO_SECRET_KEY` | `minioadmin` | Passed to Trino for MinIO catalog access |
**Hive Metastore** (`hive-metastore`):
| Variable | Value | Description |
|----------|-------|-------------|
| `SERVICE_NAME` | `metastore` | Tells Hive to run in metastore-only mode |
| `DB_DRIVER` | `derby` | Embedded Derby database for metadata |
**Superset** (`superset`):
| Variable | Value | Description |
|----------|-------|-------------|
| `SUPERSET_SECRET_KEY` | `stonks-dev-secret-key-change-me` | Flask secret key (change in production) |
| `ADMIN_USERNAME` | `admin` | Initial admin username |
| `ADMIN_PASSWORD` | `admin` | Initial admin password |
| `ADMIN_EMAIL` | `admin@stonks.local` | Initial admin email |
### Additional Configuration Variables
All application services support additional environment variables loaded via `services/shared/config.py`. These can be added to individual service `environment` blocks or to the `x-app-env` anchor as needed:
| Variable | Default | Description |
|----------|---------|-------------|
| `REDIS_DB` | `0` | Redis database number |
| `REDIS_PASSWORD` | (none) | Redis password (not needed in Docker Compose) |
| `MINIO_SECURE` | `false` | Use HTTPS for MinIO |
| `OLLAMA_BASE_URL` | `http://ollama:11434` | Ollama LLM server URL |
| `OLLAMA_MODEL` | `qwen3.5:9b` | Default LLM model for extraction |
| `OLLAMA_TIMEOUT` | `120` | Ollama request timeout (seconds) |
| `OLLAMA_MAX_RETRIES` | `2` | Max retries for Ollama requests |
| `VLLM_BASE_URL` | (empty) | vLLM server URL (if using vLLM instead of Ollama) |
| `VLLM_MODEL` | (empty) | vLLM model name (e.g. `AxionML/Qwen3.5-9B-NVFP4`) |
| `VLLM_TIMEOUT` | `120` | vLLM request timeout (seconds) |
| `VLLM_MAX_RETRIES` | `2` | Max retries for vLLM requests |
| `VLLM_TEMPERATURE` | `0.7` | vLLM sampling temperature |
| `VLLM_API_KEY` | (empty) | vLLM API key (if required) |
| `TRINO_HOST` | `localhost` | Trino hostname |
| `TRINO_PORT` | `8080` | Trino port |
| `TRINO_CATALOG` | `lakehouse` | Trino catalog name |
| `TRINO_SCHEMA` | `stonks` | Trino schema name |
| `MARKET_DATA_BASE_URL` | `https://api.polygon.io` | Polygon.io base URL |
| `MARKET_DATA_PROVIDER` | `polygon` | Market data provider |
| `BROKER_MODE` | `paper` | Broker mode: `paper` or `live` |
| `BROKER_PROVIDER` | `alpaca` | Broker provider |
| `TRADING_ENABLED` | `false` | Enable autonomous trading engine |
| `TRADING_RISK_TIER` | `moderate` | Risk tier: `conservative`, `moderate`, `aggressive` |
| `TRADING_POLLING_INTERVAL_SECONDS` | `60` | Recommendation polling interval |
| `TRADING_MAX_OPEN_POSITIONS` | `10` | Maximum concurrent open positions |
| `MACRO_ENABLED` | `true` | Enable macro signal layer |
| `COMPETITIVE_ENABLED` | `true` | Enable competitive signal layer |
| `LOG_LEVEL` | `INFO` | Logging level |
| `JSON_LOGS` | `true` | Enable structured JSON logging |
| `DEPLOY_STAGE` | (empty) | Deployment stage prefix for bucket names |
| `TZ` | `America/Los_Angeles` | Display timezone for timestamps (set on all containers) |
See `services/shared/config.py` for the complete list of all supported environment variables with their defaults.
---
## LLM Provider Configuration
Stonks Oracle supports two LLM backends: **Ollama** (local, self-hosted) and **vLLM** (high-performance inference server). The active provider is configured per-agent in the `ai_agents` database table, but the connection details come from environment variables.
### Option A: Bundled Ollama (default)
The `docker-compose.yml` includes an Ollama container. On first start, pull a model:
```bash
docker compose exec ollama ollama pull qwen3.5:9b-fast
```
No additional configuration needed — services connect to `http://ollama:11434` by default.
### Option B: External Ollama
If Ollama is already running on the host (e.g. with GPU access), create a `docker-compose.override.yml`:
```yaml
services:
ollama:
entrypoint: ["true"]
restart: "no"
ports: []
extractor:
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
environment:
OLLAMA_BASE_URL: "http://host.docker.internal:11434"
extra_hosts:
- "host.docker.internal:host-gateway"
recommendation:
environment:
OLLAMA_BASE_URL: "http://host.docker.internal:11434"
extra_hosts:
- "host.docker.internal:host-gateway"
```
This disables the bundled Ollama container and routes services to the host's instance. Replace the port if your Ollama runs on a non-standard port.
### Option C: vLLM Server
For higher throughput or quantized models (e.g. `AxionML/Qwen3.5-9B-NVFP4`), point services at a vLLM server. Add to your `.env`:
```dotenv
VLLM_BASE_URL=http://192.168.42.254:8000
VLLM_MODEL=AxionML/Qwen3.5-9B-NVFP4
VLLM_TIMEOUT=120
VLLM_TEMPERATURE=0.7
```
Then update the `ai_agents` table to use the vLLM provider:
```sql
UPDATE ai_agents SET model_provider = 'vllm', model_name = 'AxionML/Qwen3.5-9B-NVFP4' WHERE active = true;
```
Or use the API:
```bash
curl -X PUT http://localhost:8004/api/admin/agents/document-extractor \
-H 'Content-Type: application/json' \
-d '{"model_provider": "vllm", "model_name": "AxionML/Qwen3.5-9B-NVFP4"}'
```
### Option D: Mixed (Ollama + vLLM)
You can run different agents on different providers. For example, use vLLM for the high-volume extractor and Ollama for the thesis rewriter:
```sql
UPDATE ai_agents SET model_provider = 'vllm', model_name = 'AxionML/Qwen3.5-9B-NVFP4' WHERE slug = 'document-extractor';
UPDATE ai_agents SET model_provider = 'vllm', model_name = 'AxionML/Qwen3.5-9B-NVFP4' WHERE slug = 'event-classifier';
UPDATE ai_agents SET model_provider = 'ollama', model_name = 'qwen3.5:9b-fast' WHERE slug = 'thesis-rewriter';
```
Both `OLLAMA_BASE_URL` and `VLLM_BASE_URL` must be set in the environment for mixed mode.
### Automated Deployment
The `deploy-docker.sh` script handles LLM configuration automatically:
```bash
# Auto-detect host Ollama, use default model
bash deploy-docker.sh
# Specify a remote Ollama instance
bash deploy-docker.sh --ollama-url http://10.1.1.12:2701 --ollama-model qwen3.6
# Specify a different host
bash deploy-docker.sh --host user@myserver --dir /opt/stonks
```
---
## Volume Mounts and Data Persistence
Docker Compose defines five named volumes for persistent data:
| Volume | Mounted By | Mount Path | Contents |
|--------|-----------|------------|----------|
| `pgdata` | postgres | `/var/lib/postgresql/data` | PostgreSQL database files |
| `miniodata` | minio | `/data` | MinIO object storage (raw artifacts, lakehouse Parquet files) |
| `ollama_models` | ollama | `/root/.ollama` | Downloaded LLM model weights |
| `hive_data` | hive-metastore | `/opt/hive/data` | Hive metastore Derby database |
| `superset_data` | superset | `/app/superset_home` | Superset configuration and metadata |
### Bind Mounts
In addition to named volumes, several services use bind mounts for configuration:
| Service | Host Path | Container Path | Mode | Purpose |
|---------|-----------|---------------|------|---------|
| postgres | `./infra/migrations` | `/docker-entrypoint-initdb.d` | rw | SQL migrations auto-applied on first start |
| trino | `./infra/trino/catalog` | `/etc/trino/catalog` | rw | Trino catalog configuration (lakehouse, iceberg) |
| hive-metastore | `./infra/hive/core-site.xml` | `/opt/hive/conf/core-site.xml` | ro | Hadoop core-site config for MinIO access |
| hive-metastore | `./infra/hive/metastore-site.xml` | `/opt/hive/conf/metastore-site.xml` | ro | Hive metastore config |
### Resetting Data
To destroy all persistent data and start fresh:
```bash
# Stop all containers and remove named volumes
docker compose down -v
```
This removes `pgdata`, `miniodata`, `ollama_models`, `hive_data`, and `superset_data`. The next `docker compose up` will re-initialize PostgreSQL with migrations, re-create MinIO buckets (via `minio-init`), and re-download Ollama models.
To reset only specific volumes:
```bash
docker compose down
docker volume rm stonks-oracle_pgdata # Reset database only
docker compose up -d
```
> **Note**: Volume names are prefixed with the project directory name (e.g., `stonks-oracle_pgdata`). Use `docker volume ls` to see exact names.
---
## Health Checks
Every service has a health check configured. Docker Compose uses these to enforce startup ordering via `depends_on` with `condition: service_healthy`.
### Infrastructure Health Checks
| Service | Test Command | Interval | Retries |
|---------|-------------|----------|---------|
| `postgres` | `pg_isready -U stonks` | 5s | 5 |
| `redis` | `redis-cli ping` | 5s | 5 |
| `minio` | `mc ready local` | 5s | 5 |
### Application Health Checks — FastAPI Services
FastAPI services (symbol-registry, trading-engine, risk-engine, query-api) use HTTP health endpoints:
| Service | Test Command | Interval | Timeout | Retries | Start Period |
|---------|-------------|----------|---------|---------|-------------|
| `symbol-registry` | `curl -f http://localhost:8000/health` | 10s | 5s | 3 | 15s |
| `trading-engine` | `curl -f http://localhost:8000/health` | 10s | 5s | 3 | 15s |
| `risk-engine` | `curl -f http://localhost:8000/health` | 10s | 5s | 3 | 15s |
| `query-api` | `curl -f http://localhost:8000/health` | 10s | 5s | 3 | 15s |
| `dashboard` | `curl -f http://localhost:8080/` | 10s | 5s | 3 | 10s |
### Application Health Checks — Worker Services
Worker services (no HTTP endpoint) use process liveness checks:
| Service | Test Command | Interval | Timeout | Retries | Start Period |
|---------|-------------|----------|---------|---------|-------------|
| `scheduler` | `pgrep -f 'python -m services.scheduler.app'` | 10s | 5s | 3 | 15s |
| `ingestion` | `pgrep -f 'python -m services.ingestion.worker'` | 10s | 5s | 3 | 15s |
| `parser` | `pgrep -f 'python -m services.parser.worker'` | 10s | 5s | 3 | 15s |
| `extractor` | `pgrep -f 'python -m services.extractor.main'` | 10s | 5s | 3 | 15s |
| `aggregation` | `pgrep -f 'python -m services.aggregation.main'` | 10s | 5s | 3 | 15s |
| `recommendation` | `pgrep -f 'python -m services.recommendation.main'` | 10s | 5s | 3 | 15s |
| `broker-adapter` | `pgrep -f 'python -m services.adapters.broker_service'` | 10s | 5s | 3 | 15s |
| `lake-publisher` | `pgrep -f 'python -m services.lake_publisher.jobs'` | 10s | 5s | 3 | 15s |
### Verifying Service Health
```bash
# Check all service statuses
docker compose ps
# Check a specific service
docker compose ps query-api
# Inspect health check details for a container
docker inspect --format='{{json .State.Health}}' stonks-oracle-query-api-1 | python -m json.tool
```
---
## Dockerfile Build Details
### `docker/Dockerfile` — Generic Python Service Image
Used by all application services except the scheduler. Accepts a `SERVICE_CMD` build argument that determines which service the container runs.
**Base image**: `python:3.12-slim`
**Build arguments**:
| Argument | Default | Description |
|----------|---------|-------------|
| `SERVICE_CMD` | `python -m services.scheduler.app` | The command executed when the container starts |
**What gets copied**:
- `requirements.txt` → pip dependencies installed
- `services/` → all service source code
- `tests/` → test files (available for in-container testing)
- `conftest.py` → pytest configuration
**Environment variables set**:
- `PYTHONDONTWRITEBYTECODE=1` — no `.pyc` files
- `PYTHONUNBUFFERED=1` — unbuffered stdout/stderr for log visibility
- `PYTHONPATH=/app` — ensures `services.*` imports resolve
**System packages installed**: `gcc`, `libpq-dev` (PostgreSQL client library), `curl` (for health checks)
**Security**: Runs as non-root user `stonks` (UID 1000).
**How `SERVICE_CMD` works**: The `CMD` directive is `sh -c "${SERVICE_CMD}"`, so the build argument becomes the runtime command. Each service in `docker-compose.yml` overrides this via the `args.SERVICE_CMD` build parameter:
```yaml
query-api:
build:
context: .
dockerfile: docker/Dockerfile
args:
SERVICE_CMD: "uvicorn services.api.app:app --host 0.0.0.0 --port 8000"
```
### `docker/Dockerfile.scheduler` — Scheduler Image
A specialized variant of the generic Dockerfile used only by the `scheduler` service. Adds `postgresql-client` for running database migrations via `psql`.
**Additional contents**:
- `infra/migrations/` → copied to `/app/infra/migrations/` for migration execution
- `postgresql-client` system package installed
**Command**: Hardcoded `CMD ["python", "-m", "services.scheduler.app"]` (no `SERVICE_CMD` argument).
### `docker/Dockerfile.superset` — Custom Superset Image
Extends the official Apache Superset image with additional database drivers.
**Base image**: `apache/superset:latest`
**Additional packages**: `trino[sqlalchemy]`, `psycopg2-binary`, `redis`
### `frontend/Dockerfile` — Dashboard Image
Multi-stage build for the React dashboard.
**Stage 1 — Build** (base: `node:24-alpine`):
| Build Argument | Default | Description |
|---------------|---------|-------------|
| `VITE_QUERY_API_URL` | `""` | Query API base URL (empty = use relative `/api/` proxy) |
| `VITE_SYMBOL_REGISTRY_URL` | `""` | Symbol Registry base URL (empty = use relative `/registry/` proxy) |
| `VITE_RISK_ENGINE_URL` | `""` | Risk Engine base URL (empty = use relative `/risk/` proxy) |
**Stage 2 — Serve** (base: `nginxinc/nginx-unprivileged:alpine`):
- Serves the built static files on port 8080
- Uses `frontend/nginx.conf` for SPA fallback and API reverse proxying
- Proxies `/api/``query-api:8000`, `/registry/``symbol-registry:8000`, `/risk/``risk-engine:8000`, `/trading/``trading-engine:8000`
### Building Custom Images
To build a single service image locally:
```bash
# Build the query-api image
docker compose build query-api
# Build with a custom SERVICE_CMD
docker build -t my-custom-service \
--build-arg SERVICE_CMD="python -m services.my_service.main" \
-f docker/Dockerfile .
# Build the dashboard with custom API URLs
docker build -t my-dashboard \
--build-arg VITE_QUERY_API_URL="https://api.example.com" \
-f frontend/Dockerfile frontend/
# Rebuild all images
docker compose build
```
---
## Dependency Ordering
Docker Compose enforces startup order using `depends_on` with health check conditions. The dependency graph is:
```
postgres (healthy) ──┬── scheduler
├── symbol-registry
├── ingestion
├── parser
├── extractor
├── aggregation
├── recommendation
├── trading-engine
├── risk-engine
├── broker-adapter
├── lake-publisher
└── query-api
redis (healthy) ─────┬── scheduler
├── ingestion
├── parser
├── extractor
├── aggregation
├── recommendation
├── trading-engine
├── broker-adapter
└── query-api
minio (healthy) ─────┬── minio-init
├── ingestion
├── lake-publisher
└── query-api
ollama (started) ────── extractor
minio ───────────────── trino
hive-metastore ─────── trino
trino ──────────────── superset (via depends_on)
query-api (healthy) ── dashboard
```
Services with `condition: service_healthy` wait until the dependency's health check passes. The `extractor` depends on `ollama` with `condition: service_started` (no health check — Ollama may take time to load models).
---
## Operational Commands
### Starting Services
```bash
# Start all services in the background
docker compose up -d
# Start only infrastructure (useful for local development)
docker compose up -d postgres redis minio minio-init ollama
# Start a specific service and its dependencies
docker compose up -d query-api
```
### Stopping Services
```bash
# Stop all services (preserves volumes)
docker compose down
# Stop all services and remove volumes (full reset)
docker compose down -v
# Stop a specific service
docker compose stop trading-engine
```
### Restarting Services
```bash
# Restart a specific service
docker compose restart query-api
# Restart with a fresh build
docker compose up -d --build query-api
# Force recreate a service (picks up compose file changes)
docker compose up -d --force-recreate query-api
```
### Viewing Logs
```bash
# Follow logs for all services
docker compose logs -f
# Follow logs for a specific service
docker compose logs -f query-api
# View last 50 lines of a service's logs
docker compose logs --tail=50 ingestion
# View logs for multiple services
docker compose logs -f scheduler ingestion extractor
```
### Scaling Replicas
```bash
# Scale a worker service to 3 replicas
docker compose up -d --scale ingestion=3
# Scale multiple services
docker compose up -d --scale ingestion=3 --scale extractor=2
# Scale back to 1
docker compose up -d --scale ingestion=1
```
> **Note**: Scaling works best for worker services (ingestion, parser, extractor, aggregation, recommendation, broker-adapter, lake-publisher) that consume from Redis queues. Do not scale FastAPI services that expose host ports without adjusting port mappings.
### Inspecting Services
```bash
# List all services and their status
docker compose ps
# View resource usage
docker compose top
# Execute a command inside a running container
docker compose exec query-api python -c "from services.shared.config import load_config; print(load_config())"
# Open a shell in a container
docker compose exec postgres psql -U stonks -d stonks
```
### Full Reset
```bash
# Nuclear option: stop everything, remove volumes, rebuild, restart
docker compose down -v
docker compose build --no-cache
docker compose up -d
```
This destroys all data (database, object storage, model weights, metastore, Superset config) and starts from scratch. PostgreSQL migrations are re-applied automatically. MinIO buckets are re-created by `minio-init`. Ollama models must be re-downloaded.
---
## MinIO Bucket Initialization
The `minio-init` service runs once on startup and creates the required object storage buckets:
| Bucket | Purpose |
|--------|---------|
| `stonks-raw-market` | Raw market data from Polygon.io |
| `stonks-raw-news` | Raw news articles |
| `stonks-raw-filings` | Raw SEC filings |
| `stonks-normalized` | Normalized/parsed documents |
| `stonks-llm-prompts` | LLM prompt archives |
| `stonks-llm-results` | LLM extraction results |
| `stonks-lakehouse` | Parquet fact tables for Trino |
| `stonks-audit` | Audit trail artifacts |
Access the MinIO console at `http://localhost:9001` (credentials: `minioadmin` / `minioadmin`).
---
## Dashboard Reverse Proxy
The dashboard container runs nginx with reverse proxy rules that route API requests to backend services using Docker Compose service names:
| Path | Proxied To | Service |
|------|-----------|---------|
| `/api/` | `http://query-api:8000` | Query API |
| `/registry/` | `http://symbol-registry:8000/` | Symbol Registry API |
| `/risk/` | `http://risk:8000/` | Risk Engine (via network alias) |
| `/trading/` | `http://trading-engine:8000/` | Trading Engine API |
The `risk-engine` service has a network alias of `risk` in `docker-compose.yml` so the nginx upstream resolves correctly.
All other paths serve the React SPA with `try_files` fallback to `index.html`.
---
## Troubleshooting
### Service won't start
Check dependency health:
```bash
docker compose ps postgres redis minio
```
If infrastructure services are unhealthy, application services will wait indefinitely. Check infrastructure logs:
```bash
docker compose logs postgres
```
### Database migration errors
Migrations in `./infra/migrations/` are applied by PostgreSQL's `docker-entrypoint-initdb.d` mechanism, which only runs on first database initialization. If you need to re-run migrations:
```bash
docker compose down -v # Remove pgdata volume
docker compose up -d # Migrations re-applied on fresh init
```
### Ollama model not available
The extractor service needs an LLM model loaded. Pull a model manually:
```bash
# If using bundled Ollama container:
docker compose exec ollama ollama pull qwen3.5:9b-fast
# If using host Ollama:
ollama pull qwen3.5:9b-fast
# If using vLLM, ensure the model is loaded on the vLLM server
curl http://your-vllm-host:8000/v1/models
```
### Ollama port conflict (address already in use)
If Ollama is already running on the host, the bundled container will fail to bind port 11434. Use the external Ollama configuration described in the "LLM Provider Configuration" section above, or use `deploy-docker.sh` which handles this automatically.
### Port conflicts
If a port is already in use, modify the host port mapping in `docker-compose.yml`:
```yaml
query-api:
ports:
- "9004:8000" # Changed from 8004 to 9004
```
+915
View File
@@ -0,0 +1,915 @@
# Stonks Oracle — Mathematical Reference
Every equation, formula, threshold, and constant used in the signal processing, aggregation, recommendation, and trading pipeline. Organized by pipeline stage.
Code references are provided so each formula can be traced to its implementation.
---
## 1. Signal Scoring
**Source:** `services/aggregation/scoring.py`
### 1.1 Combined Signal Weight
Each document signal receives a composite weight:
```
W_combined = G_conf × W_recency × W_credibility × (1 + B_novelty) × M_context
```
| Component | Symbol | Formula | Range |
|---|---|---|---|
| Confidence gate | G_conf | 1 if extraction_confidence ≥ 0.2, else 0 | {0, 1} |
| Recency decay | W_recency | 2^(t_age / t_half) | [0.01, 1.0] |
| Credibility | W_credibility | clamp(credibility, 0.1, 1.0)^α | [0.1, 1.0] |
| Novelty bonus | B_novelty | novelty_score × 0.25 | [0, 0.25] |
| Market context | M_context | 1 + boost_vol + boost_vol_surge | [1.0, 1.45] |
### 1.2 Recency Decay
```
W_recency = max( 2^(t_age / t_half), 0.01 )
```
where `t_age` is document age in hours and half-lives by window are:
| Window | t_half (hours) |
|---|---|
| intraday | 2 |
| 1d | 12 |
| 7d | 72 |
| 30d | 240 |
| 90d | 720 |
### 1.3 Credibility Weight
```
W_credibility = clamp(c_raw, 0.1, 1.0)^α where α = 1.0 (default)
```
α > 1 penalizes low-credibility sources more aggressively; α < 1 flattens the curve.
### 1.4 Market Context Multiplier
```
boost_vol = min( ln(1 + max(σ 1.0, 0)) × 0.15, 0.30 )
boost_surge = 0.15 if ΔV% > 50%, else 0
M_context = 1.0 + boost_vol + boost_surge
```
where σ is price volatility and ΔV% is volume change percentage.
### 1.5 Weighted Sentiment Average
```
S_avg = Σ(W_combined_i × impact_i × sentiment_i) / Σ(W_combined_i × impact_i)
```
- sentiment_i ∈ {+1.0 (positive), 1.0 (negative), 0.0 (neutral/mixed)}
- impact_i ∈ [0, 1] from extraction
- Returns 0.0 when denominator = 0
---
## 1B. Probabilistic Signal Scoring (Feature-Flagged)
**Source:** `services/aggregation/scoring.py`
**Active when:** `probabilistic_scoring_enabled = true` in `risk_configs.config` JSONB
When the probabilistic pipeline is enabled, the combined weight formula changes:
### 1B.1 Combined Signal Weight (Probabilistic)
```
W_combined = G_sigmoid × W_recency(adaptive) × W_credibility × (1 + B_novelty) × R_info × F_accuracy × M_regime
```
| Component | Symbol | Formula | Range |
|---|---|---|---|
| Sigmoid gate | G_sigmoid | σ(k·(x midpoint)) = 1/(1+e^(5·(x0.5))) | (0, 1) |
| Adaptive recency | W_recency | 2^(t_age / τ_adaptive) | [0.01, 1.0] |
| Credibility | W_credibility | same as heuristic | [0.1, 1.0] |
| Novelty bonus | B_novelty | same as heuristic | [0, 0.25] |
| Information gain | R_info | 1 + λ·(log₂ P(event_type)) | [1.0, 3.0] |
| Source accuracy | F_accuracy | 0.5 + accuracy_ratio (if samples ≥ 10, else 1.0) | [0.5, 1.5] |
| Regime multiplier | M_regime | 1 + 0.15·|z_r| + 0.10·|z_v| | [1.0, 2.5] |
### 1B.2 Sigmoid Confidence Gate
Replaces the binary 0/1 gate with a smooth transition:
```
G_sigmoid = σ(k·(x m)) = 1 / (1 + e^(k·(xm)))
```
Default: k = 5.0, m = 0.5. At x=0.5 → 0.5; at x=0.2 → ~0.18; at x=0.8 → ~0.82.
### 1B.3 Information Gain (Surprise Weighting)
```
R_info = min(1 + λ·(log₂ P(event_type)), 3.0)
```
| Event Type | P(event_type) | R_info (λ=0.3) |
|---|---|---|
| earnings | 0.25 | 1.60 |
| dividend | 0.15 | 1.84 |
| product_launch | 0.10 | 2.00 |
| regulatory | 0.08 | 2.07 |
| management_change | 0.06 | 2.19 |
| legal | 0.05 | 2.29 |
| restructuring | 0.04 | 2.39 |
| m_and_a | 0.03 | 2.56 |
| unknown | 0.10 (default) | 2.00 |
### 1B.4 Adaptive Recency Decay
```
τ_adaptive = τ_base × (1 + β_impact) × (1 + β_surprise) × (1 + β_market)
```
| Factor | Formula | Range |
|---|---|---|
| β_impact | impact_score × 1.0 | [0, 1.0] |
| β_surprise | (R_info 1) / 2 × 1.0 | [0, 1.0] |
| β_market | (M_regime 1) / 0.45 × 0.5 | [0, 0.5] |
Maximum adaptive half-life: 6× base (when all factors at max).
Minimum: τ_base (adaptive decay is never faster than fixed).
### 1B.5 Regime Multiplier
```
z_r = (r_t μ_20) / σ_20 (return z-score)
z_v = (ln(V_t) μ_V) / σ_V (log-volume z-score)
M_regime = clamp(1 + 0.15·|z_r| + 0.10·|z_v|, 1.0, 2.5)
```
Defaults to 1.0 when market data unavailable or σ = 0.
### 1B.6 Source Accuracy Factor
```
F_accuracy = 0.5 + clamp(accuracy_ratio, 0, 1) if sample_count ≥ 10
F_accuracy = 1.0 if sample_count < 10
```
Stored in `source_accuracy` table, updated asynchronously from realized 7-day price outcomes.
---
## 2. Trend Summary Assembly
**Source:** `services/aggregation/worker.py`
### 2.1 Trend Direction
| Condition | Direction |
|---|---|
| S_avg ≥ 0.15 | Bullish |
| S_avg ≤ 0.15 | Bearish |
| contradiction > 0.10 AND |S_avg| < 0.30 | Mixed |
| otherwise | Neutral |
### 2.2 Trend Strength
```
strength = min(|S_avg|, 1.0)
```
### 2.3 Contradiction Score
**Source:** `services/aggregation/contradiction.py`
```
contradiction = W_minority / (W_positive + W_negative)
```
where:
```
W_positive = Σ(W_combined_i × impact_i) for signals with sentiment > 0
W_negative = Σ(W_combined_i × impact_i) for signals with sentiment < 0
W_minority = min(W_positive, W_negative)
```
Range: [0, 1]. 0 = full agreement, 0.5 = equal-weight disagreement.
### 2.4 Trend Confidence
```
confidence = clamp(0.3 × F_count + 0.3 × C_avg + 0.4 × A_agreement P_contradiction, 0, 1)
```
| Component | Formula |
|---|---|
| F_count (source count) | min(N_unique / 15, 0.8) |
| C_avg (extraction confidence) | mean of extraction confidences |
| A_agreement (signal agreement) | fraction_same_direction × min(1, log₂(N_unique + 1) / log₂(8)) |
| P_contradiction | contradiction_score × 0.4 |
---
## 2B. Probabilistic Trend Assembly (Feature-Flagged)
**Source:** `services/aggregation/worker.py`, `services/aggregation/bayesian.py`
**Active when:** `probabilistic_scoring_enabled = true`
### 2B.1 Bayesian Posterior Accumulation
```
L_t = Σ(W_combined_i × sentiment_i) (log-likelihood)
P_bull = σ(L_t) = 1 / (1 + e^(L_t)) (bullish probability)
α = 1 + W_bull (W_bull = Σ W_combined for positive signals)
β = 1 + W_bear (W_bear = Σ W_combined for negative signals)
C_bayesian = 1 4αβ / (α + β)² (Bayesian confidence)
H = P_bull·log₂(P_bull) (1P_bull)·log₂(1P_bull) (Shannon entropy)
```
Uninformative prior (no signals): P_bull=0.5, α=1, β=1, C=0, H=1.0.
### 2B.2 Entropy-Based Direction
| Condition | Direction |
|---|---|
| H > 0.9 | Mixed |
| P_bull > 0.65 | Bullish |
| P_bull < 0.35 | Bearish |
| otherwise | Neutral |
### 2B.3 Bayesian Trend Confidence
```
confidence = clamp(0.5 × C_bayesian + 0.25 × F_count + 0.25 × C_avg_credibility P_contradiction, 0, 1)
```
| Component | Formula |
|---|---|
| C_bayesian | 1 4αβ/(α+β)² from Beta posterior |
| F_count | min(N_unique_sources / 15, 0.8) |
| C_avg_credibility | mean credibility weight across active signals |
| P_contradiction | contradiction_entropy × regime.contradiction_penalty_multiplier |
### 2B.4 Weighted Disagreement Entropy (Contradiction)
**Source:** `services/aggregation/contradiction.py`
```
f_pos = W_positive / (W_positive + W_negative)
f_neg = 1 f_pos
H_contradiction = f_pos·log₂(f_pos) f_neg·log₂(f_neg)
contradiction_score = H_contradiction × min(1.0, (W_pos + W_neg) / W_threshold)
```
W_threshold default = 5.0. Returns 0.0 when only one direction exists.
### 2B.5 Regime Detection
**Source:** `services/aggregation/regime.py`
```
R = sign(EMA_20 EMA_100) (trend indicator)
V_r = σ_20 / σ_100 (volatility ratio)
```
| Condition | Regime | Threshold | Contradiction Mult |
|---|---|---|---|
| V_r > 1.5 | Panic | ±0.10 | 0.4 |
| R ≠ 0 AND V_r < 1.2 | Trend-following | ±0.15 | 0.4 |
| R = 0 AND V_r < 1.0 | Mean-reversion | ±0.20 | 0.4 |
| otherwise | Uncertainty | ±0.15 | 0.6 |
Falls back to Uncertainty when data < 100 days or σ = 0.
---
## 3. Macro Impact Scoring (Layer 2)
**Source:** `services/aggregation/interpolation.py`
### 3.1 Overlap Components
**Geographic overlap:**
```
O_geo = Σ revenue_pct_r for each event region r in company's revenue mix
```
Range: [0, 1]
**Supply chain overlap:**
```
O_supply = |event_regions ∩ supply_regions| / |supply_regions|
```
**Commodity overlap:**
```
O_commodity = |event_commodities ∩ company_commodities| / |company_commodities|
```
**Sector overlap:**
```
O_sector = 1.0 if company_sector ∈ event_affected_sectors, else 0.0
```
### 3.2 Raw Macro Impact Score
```
S_raw = W_severity × (0.35 × O_geo + 0.25 × O_supply + 0.25 × O_commodity + 0.15 × O_sector)
```
Severity weights:
| Severity | W_severity |
|---|---|
| critical | 1.0 |
| high | 0.75 |
| moderate | 0.5 |
| low | 0.25 |
### 3.3 Resilience Modifier
For international events, the raw score is adjusted by market position:
```
S_final = clamp(S_raw × R_tier, 0, 1)
```
| Market Position Tier | R_tier |
|---|---|
| Global leader | 0.70 |
| Multinational | 0.85 |
| Regional | 1.00 |
| Domestic | 1.20 |
For domestic-only events, R_tier = 1.0 regardless of tier.
### 3B. Multiplicative Macro Exposure (Probabilistic)
**Active when:** `probabilistic_scoring_enabled = true`
```
S_raw = W_severity × (1 Π_k(1 w_k × O_k))
= W_severity × (1 (10.35·O_geo)(10.25·O_supply)(10.25·O_commodity)(10.15·O_sector))
```
Zero overlap → 0.0. Max overlap (all 1.0) → severity × 0.689.
### 3B.1 Conditional Macro Integration
When both company and macro signals exist:
```
modifier = clamp(1 + M_macro × sign_alignment, 0.5, 1.5)
S_adjusted = S_company × modifier
```
sign_alignment = +1 (agree), 1 (disagree), 0 (neutral/mixed).
When only macro signals exist: additive fallback with weight 0.3.
When only company signals exist: modifier = 1.0.
### 3.4 Macro Impact Confidence
```
confidence = min(event_confidence × min(O_total + 0.3, 1.0), 1.0)
```
where O_total = O_geo + O_supply + O_commodity + O_sector.
### 3.5 Accelerated Staleness Decay
For short-term events older than 48 hours:
```
decay_standard = e^(0.693 × t_age_hours / t_half_hours) (t_half default = 168h)
decay_accelerated = decay_standard × 0.5
```
### 3.6 Macro Signal as WeightedSignal
When merged into the aggregation engine:
```
impact_score_macro = macro_impact_score × W_macro (W_macro = 0.3 default)
sentiment_value = +1 if positive, 1 if negative
```
Recency decay uses the global event's publication time.
---
## 4. Competitive Signals (Layer 3)
### 4.1 Pattern Confidence
**Source:** `services/aggregation/pattern_matcher.py`
```
confidence = F_sample × 0.4 + F_consistency × 0.4 + F_recency × 0.2
```
| Factor | Formula |
|---|---|
| F_sample | min(N_samples / 20, 1.0) |
| F_consistency | max(pct_bullish, pct_bearish) |
| F_recency | 1.0 if age ≤ 7d; 0.7 if age ≤ 90d; 0.4 otherwise |
**Modifiers:**
- Major corporate decision (m&a, earnings, legal): confidence × 1.3
- Insufficient data (N_samples < min_pattern_samples): cap at 0.25
- Stale data (age > staleness_window_days): confidence × staleness_decay_penalty
**Lookback windows:**
- Routine signals: 180 days
- Major corporate decisions: 365 days
### 4.2 Cross-Company Signal Strength
**Source:** `services/aggregation/signal_propagation.py`
```
S_competitive = clamp(S_pattern_avg × R_relationship × C_pattern × I_source, 0, 1)
```
| Component | Description |
|---|---|
| S_pattern_avg | Average historical outcome strength [0, 1] |
| R_relationship | Relationship strength from competitor_relationships [0, 1] |
| C_pattern | Pattern confidence from §4.1 |
| I_source | Source document's impact_score [0, 1] |
**Threshold gate:** Skipped if R_relationship < propagation_strength_threshold (default 0.2).
### 4B. Graph-Distance Attenuation (Probabilistic)
**Active when:** `probabilistic_scoring_enabled = true`
```
S_transfer = S_source × ρ_historical × e^(d_network)
```
| Component | Description |
|---|---|
| S_source | Source signal strength |
| ρ_historical | 90-day rolling Pearson correlation (default 0.3 same-sector, 0.1 cross-sector) |
| d_network | Shortest path in competitor graph (capped at 3) |
No propagation when d_network > 3 (e^(3) ≈ 0.05).
### 4.3 Competitive Signal as WeightedSignal
```
impact_score_competitive = S_competitive × W_competitive (W_competitive = 0.2 default)
direction = majority historical outcome (bullish or bearish)
```
---
## 5. Trend Projection
**Source:** `services/aggregation/projection.py`
### 5.1 Trend Momentum
```
momentum = S_current_signed S_previous_signed
```
where `S_signed = direction_sign × strength` (bullish = +1, bearish = 1, neutral = 0).
When no previous data exists:
```
momentum = direction_sign × strength × 0.5
```
Range: [1, 1]
### 5.2 Macro Decay Projection
For each active macro event projected forward by `H` days:
```
F_future = 2^((t_current + H) / t_half)
I_projected = macro_impact_score × F_future × W_severity
```
Decay half-lives:
| Duration | t_half (days) |
|---|---|
| short_term | 1.0 |
| medium_term | 7.0 |
| long_term | 30.0 |
Aggregate direction: bullish if W_pos > 1.2 × W_neg; bearish if W_neg > 1.2 × W_pos; mixed if both > 0.
### 5.3 Projection Blending
```
W_macro_blend = min(S_macro_projected × 0.4, 0.4)
W_company = 1.0 W_macro_blend
S_blended = W_company × S_momentum_projected + W_macro_blend × S_macro_signed
```
**Catalyst boost:** `min(N_catalysts × 0.02, 0.1)` added to projected strength.
**Projected confidence:**
```
C_projected = C_base × 0.8 + min(S_macro × 0.15, 0.1)
```
**Divergence detection:** Flagged when projected direction ≠ current trend direction.
### 5B. Exponentially Weighted Momentum (Probabilistic)
**Source:** `services/aggregation/projection.py`
**Active when:** `probabilistic_scoring_enabled = true`
```
M_t = Σ_{k=0}^{K-1} λ^k × ΔS_{t-k} (λ = 0.7, K ≤ 10)
M_normalized = M_t / Σ_{k=0}^{K-1} λ^k (range: [1, 1])
M_adj = clamp(M_normalized / max(σ_20, 0.01), 2.0, 2.0)
```
Falls back to heuristic momentum when < 2 historical cycles available.
---
## 6. Data Quality Suppression
**Source:** `services/recommendation/suppression.py`
### 6.1 Data Quality Score
```
Q = 0.4 × Q_confidence + 0.3 × Q_freshness + 0.3 × Q_coverage
```
| Component | Formula |
|---|---|
| Q_confidence | min(C_avg_extraction / 0.8, 1.0) |
| Q_freshness | max(0, 1 t_newest_hours / 168) |
| Q_coverage | (N_valid / N_total) × min(N_valid / 10, 1.0) |
**Suppression triggers** (any one → informational only):
| Check | Threshold |
|---|---|
| Avg extraction confidence | < 0.40 |
| Evidence staleness | > 168 hours (7 days) |
| Source type diversity | < 1 distinct type |
| Extraction failure rate | > 50% |
| Valid document count | < 2 |
| Data quality score | < 0.30 |
### 6.2 Safety Suppression
- **Macro-only:** If trend driven solely by macro signals with zero company evidence → forced informational
- **Pattern-only:** If trend driven solely by pattern/competitive signals with no company or macro support → forced informational
---
## 7. Recommendation Eligibility
**Source:** `services/recommendation/eligibility.py`
### 7.1 Gate Checks (all must pass)
| Check | Threshold |
|---|---|
| Confidence | ≥ 0.35 |
| Trend strength | ≥ 0.10 |
| Contradiction score | ≤ 0.60 |
| Evidence count | ≥ 2 |
| Direction | ≠ neutral |
### 7.2 Action Mapping
| Condition | Action |
|---|---|
| Bullish AND strength ≥ 0.25 | BUY |
| Bearish AND strength ≥ 0.25 | SELL |
| Directional AND confidence ≥ 0.50 | HOLD |
| Mixed or weak | WATCH |
### 7.3 Mode Escalation
| Mode | Requirements |
|---|---|
| live_eligible | confidence ≥ 0.70, contradiction ≤ 0.25, evidence ≥ 5 |
| paper_eligible | confidence ≥ 0.50 |
| informational | everything else (WATCH/HOLD always informational) |
### 7B. Expected Value Gate (Probabilistic)
**Active when:** `probabilistic_scoring_enabled = true`
```
R_up = strength × σ_20 × √(horizon_days)
R_down = (1 strength) × σ_20 × √(horizon_days)
EV = P_bull × R_up (1 P_bull) × R_down
```
| Horizon window | horizon_days |
|---|---|
| intraday / 1d | 1 |
| 7d | 7 |
| 30d | 30 |
| 90d | 90 |
- EV > 0.005 (0.5% expected return): recommendation proceeds through existing gates
- EV ≤ 0.005: forced to informational mode regardless of confidence/strength
- All existing eligibility gates (§7.1) remain as additional requirements
### 7.4 Position Sizing
```
portfolio_pct = base + C_factor × S_factor × range × P_contradiction × P_evidence
```
| Component | Formula | Default |
|---|---|---|
| base | base_portfolio_pct | 0.01 (1%) |
| range | max_portfolio_pct base_portfolio_pct | 0.09 (9%) |
| C_factor | confidence_sizing_weight × confidence | 0.8 × confidence |
| S_factor | 0.5 + 0.5 × trend_strength | [0.5, 1.0] |
| P_contradiction | 1 (contradiction_penalty × contradiction_score) | penalty = 0.5 |
| P_evidence | 0.50 if evidence < 3; 0.75 if evidence < 5; 1.0 otherwise | |
Clamped to [base × 0.5, max_portfolio_pct].
**Max loss percentage** uses the same structure with base = 0.003 (0.3%) and max = 0.02 (2%).
---
## 8. Trading Engine — Position Sizing
**Source:** `services/trading/position_sizer.py`
### 8.1 Base Allocation
```
raw_pct = (max_position_pct × 0.5) × (confidence / min_confidence) × multiplier
clamped_pct = min(raw_pct, max_position_pct)
dollar_amount = min(active_pool × clamped_pct, absolute_position_cap)
```
### 8.2 Correlation Reduction
```
ρ_avg = Σ(ρ_i × w_i) / Σ(w_i) for existing positions
```
| ρ_avg | Action |
|---|---|
| > 0.8 | Reject order |
| 0.5 < ρ_avg ≤ 0.8 | Reduce: factor = 1 (ρ_avg 0.5) / 0.3 |
| ≤ 0.5 | No reduction |
### 8.3 Sector Exposure Reduction
```
available = max(max_sector_pct × active_pool current_sector_exposure, 0)
dollar_amount = min(dollar_amount, available)
```
### 8.4 Diversification Bonus
If < 3 sectors held AND entering a new sector: dollar_amount × 1.2 (capped at max_position_pct).
### 8.5 Earnings Proximity
| Days to earnings | Action |
|---|---|
| ≤ 1 | Reject |
| 13 | 50% reduction |
| > 3 | No adjustment |
### 8.6 Portfolio Heat Check
```
heat_new = dollar_amount × atr_multiplier × 0.02
heat_max = max_portfolio_heat × active_pool
Reject if: heat_current + heat_new > heat_max
```
### 8.7 Share Rounding
```
shares = floor(dollar_amount / current_price)
final_dollar = shares × current_price
```
Reject if shares = 0.
---
## 9. Stop-Loss and Take-Profit
**Source:** `services/trading/stop_loss_manager.py`
### 9.1 Initial Levels
```
stop_distance = ATR × M_atr
stop_loss = entry_price stop_distance
take_profit = entry_price + stop_distance × R_reward_risk
```
| Trade type | M_atr | R_reward_risk |
|---|---|---|
| Standard | risk_tier.stop_loss_atr_multiplier | risk_tier.reward_risk_ratio |
| Micro-trade | 1.0 | 1.5 |
### 9.2 Dynamic Tightening
| Condition | Effective multiplier |
|---|---|
| High-severity macro event | base × 0.5 |
| Earnings within 3 days | base × 0.7 |
| Portfolio heat > 80% of max | base × 0.7 |
| Normal | base |
### 9.3 Trailing Stop Activation
Activates when:
```
favorable_move = current_price entry_price > 0.5 × (take_profit entry_price)
```
Once active, stop-loss floor = entry_price (breakeven).
---
## 10. Risk Management
### 10.1 Position Limits
**Source:** `services/risk/engine.py`
| Limit | Default | Formula |
|---|---|---|
| Max position % | 5% | position_value / portfolio_value ≤ 0.05 |
| Max position value | $10,000 | existing + new ≤ $10,000 |
| Max shares/order | 1,000 | quantity ≤ 1,000 |
| Max sector % | 25% | sector_value / portfolio_value ≤ 0.25 |
| Max daily loss % | 2% | |daily_pnl| / portfolio_value ≤ 0.02 |
| Max daily loss $ | $1,000 | |daily_pnl| ≤ $1,000 |
| Max daily trades | 20 | trade_count < 20 |
### 10.2 Order Clamping
**Source:** `services/risk/engine.py``clamp_order_to_position_limits()`
When a buy order exceeds position limits, instead of rejecting:
```
max_allowed_value = min(
max_position_value existing_value,
max_position_pct × portfolio_value existing_value
)
clamped_shares = min( floor(max_allowed_value / price_per_share), max_shares_per_order )
```
### 10.3 News Shock Lockout
Trigger: impact_score ≥ 0.80 for catalyst ∈ {earnings, legal, m_and_a}
Duration: 60 minutes (configurable)
### 10.4 Symbol Cooldown
Duration: 15 minutes between trades on same symbol.
Max concurrent positions per symbol: 1.
---
## 11. Circuit Breaker
**Source:** `services/trading/circuit_breaker.py`
| Trigger | Condition | Cooldown |
|---|---|---|
| Daily loss | |daily_pnl| / portfolio_value > 0.05 | 2 hours |
| Single position | position_loss_pct > 0.15 | 48 hours |
| Volatility | ≥ 3 stop-losses within 30-minute window | 2 hours |
---
## 12. Risk Tier Auto-Adjustment
**Source:** `services/trading/risk_tier_controller.py`
Tiers: conservative → moderate → aggressive
**Downgrade** (any one triggers, drops one level):
- 30-day win rate < 40%
- Current drawdown > 15%
**Upgrade** (all must be true, raises one level):
- 30-day win rate > 55%
- Reserve pool > 20% of portfolio
- Current drawdown < 5%
---
## 13. Portfolio Rebalancing
**Source:** `services/trading/rebalancer.py`
### 13.1 Single-Stock Rebalancing
```
excess = market_value max_position_pct × active_pool
sell_qty = min( floor(excess / current_price), position_quantity )
```
### 13.2 Sector Rebalancing
```
sector_excess = Σ(market_value_i) max_sector_pct × active_pool
```
Sell from lowest-confidence positions first until excess is covered.
### 13.3 Max Positions Enforcement
```
excess_count = N_positions max_positions
```
Sell entire lowest-confidence positions until count is within limit.
---
## Constants Summary
| Constant | Value | Location |
|---|---|---|
| Confidence gate floor | 0.20 | scoring.py |
| Min recency weight | 0.01 | scoring.py |
| Credibility floor/ceiling | 0.10 / 1.0 | scoring.py |
| Novelty bonus max | 0.25 (25%) | scoring.py |
| Volatility boost threshold | 1.0 price units | scoring.py |
| Volatility boost max | 0.30 (30%) | scoring.py |
| Volume surge threshold | 50% | scoring.py |
| Volume surge boost | 0.15 (15%) | scoring.py |
| Bullish/bearish threshold | ±0.15 | worker.py |
| Mixed threshold | contradiction > 0.10, |S| < 0.30 | worker.py |
| Macro signal weight | 0.30 | config.py |
| Competitive signal weight | 0.20 | config.py |
| Macro confidence threshold | 0.40 | interpolation.py |
| Staleness accelerated decay | 0.50× | interpolation.py |
| Short-term staleness hours | 48 | interpolation.py |
| Pattern min samples | configurable | pattern_matcher.py |
| Major decision weight multiplier | 1.3× | pattern_matcher.py |
| Routine lookback | 180 days | pattern_matcher.py |
| Major decision lookback | 365 days | pattern_matcher.py |
| Propagation strength threshold | 0.20 | signal_propagation.py |
| Data quality min score | 0.30 | suppression.py |
| Evidence staleness max | 168 hours (7 days) | suppression.py |
| Recommendation min confidence | 0.35 | eligibility.py |
| Recommendation min strength | 0.10 | eligibility.py |
| Action strength threshold | 0.25 | eligibility.py |
| Live confidence threshold | 0.70 | eligibility.py |
| Paper confidence threshold | 0.50 | eligibility.py |
| Base portfolio allocation | 1% | eligibility.py |
| Max portfolio allocation | 10% | eligibility.py |
| Circuit breaker daily loss | 5% | circuit_breaker.py |
| Circuit breaker single position | 15% | circuit_breaker.py |
| Stop-loss cluster threshold | 3 hits / 30 min | circuit_breaker.py |
| Tier downgrade win rate | < 40% | risk_tier_controller.py |
| Tier upgrade win rate | > 55% | risk_tier_controller.py |
| Tier upgrade max drawdown | < 5% | risk_tier_controller.py |
| Tier upgrade min reserve | > 20% | risk_tier_controller.py |
| **Probabilistic pipeline** | | |
| Sigmoid steepness (k) | 5.0 | scoring.py |
| Sigmoid midpoint (m) | 0.5 | scoring.py |
| Info gain lambda (λ) | 0.3 | scoring.py |
| Info gain max clamp | 3.0 | scoring.py |
| Default base rate | 0.10 | scoring.py |
| Adaptive decay impact scale | 1.0 | scoring.py |
| Adaptive decay surprise scale | 1.0 | scoring.py |
| Adaptive decay market scale | 0.5 | scoring.py |
| Regime return weight | 0.15 | scoring.py |
| Regime volume weight | 0.10 | scoring.py |
| Regime multiplier max | 2.5 | scoring.py |
| Source accuracy min samples | 10 | source_accuracy.py |
| Contradiction W_threshold | 5.0 | contradiction.py |
| EMA short period | 20 days | regime.py |
| EMA long period | 100 days | regime.py |
| Panic volatility ratio | > 1.5 | regime.py |
| Trend-following vol ratio | < 1.2 | regime.py |
| Mean-reversion vol ratio | < 1.0 | regime.py |
| Panic threshold | ±0.10 | regime.py |
| Mean-reversion threshold | ±0.20 | regime.py |
| Uncertainty contradiction mult | 0.6 | regime.py |
| EW momentum decay (λ) | 0.7 | projection.py |
| EW momentum max lags (K) | 10 | projection.py |
| Volatility floor (σ min) | 0.01 | projection.py |
| Momentum clamp | ±2.0 | projection.py |
| EV threshold | 0.005 (0.5%) | eligibility.py |
| Graph distance max | 3 | signal_propagation.py |
| Default correlation (same-sector) | 0.3 | signal_propagation.py |
| Default correlation (cross-sector) | 0.1 | signal_propagation.py |
+660
View File
@@ -0,0 +1,660 @@
# Helm Chart Configuration Reference
Complete reference for the Stonks Oracle Helm chart at `infra/helm/stonks-oracle/`.
| | |
|---|---|
| **Chart name** | `stonks-oracle` |
| **Chart version** | `0.1.0` |
| **App version** | `1.0.0` |
| **Chart type** | `application` |
Install with:
```bash
helm upgrade --install stonks-oracle infra/helm/stonks-oracle -n stonks-oracle
```
Override values per stage:
```bash
# Beta
helm upgrade --install stonks-oracle infra/helm/stonks-oracle \
-n stonks-oracle-beta -f infra/helm/stonks-oracle/values-beta.yaml
# Paper trading
helm upgrade --install stonks-oracle infra/helm/stonks-oracle \
-n stonks-oracle -f infra/helm/stonks-oracle/values-paper.yaml
```
---
## Table of Contents
- [image — Global Image Settings](#image--global-image-settings)
- [pipelineEnabled — Pipeline Toggle](#pipelineenabled--pipeline-toggle)
- [services — Service Deployments](#services--service-deployments)
- [config — ConfigMap Environment Variables](#config--configmap-environment-variables)
- [secrets — Kubernetes Secrets](#secrets--kubernetes-secrets)
- [ingress — Ingress Configuration](#ingress--ingress-configuration)
- [Analytics Stack — Trino, Hive Metastore, Superset](#analytics-stack--trino-hive-metastore-superset)
- [networkPolicies — Network Policy Configuration](#networkpolicies--network-policy-configuration)
- [Value Override Files](#value-override-files)
---
## `image` — Global Image Settings
Controls the container image registry, pull policy, and tag for all service deployments. Each service image is resolved as `{registry}/{service.image}:{tag}`.
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `image.registry` | string | `registry.celestium.life/stonks-oracle` | Container registry prefix. Each service appends its `image` name to this. |
| `image.pullPolicy` | string | `Always` | Kubernetes `imagePullPolicy`. Use `Always` for latest-tag workflows. |
| `image.tag` | string | `latest` | Image tag applied to all services. CI overrides this with the Git SHA via `--set image.tag=<sha>`. |
Example override:
```bash
helm upgrade --install stonks-oracle infra/helm/stonks-oracle \
--set image.tag=abc1234
```
---
## `pipelineEnabled` — Pipeline Toggle
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `pipelineEnabled` | bool | `true` | Master toggle for the data pipeline. |
When `false`, all services with `pipeline: true` in their definition are scaled to **0 replicas**. API-tier and trading-tier services continue running normally.
**Affected services** (scaled to 0 when disabled): scheduler, ingestion, parser, extractor, aggregation, recommendation, broker-adapter, lake-publisher.
**Unaffected services** (always run): symbol-registry, query-api, trading-engine, risk-engine, dashboard.
The replica count logic in the deployment template:
```yaml
replicas: {{ if and (hasKey $svc "pipeline") $svc.pipeline (not .Values.pipelineEnabled) }}0{{ else }}{{ $svc.replicas }}{{ end }}
```
---
## `services` — Service Deployments
Each key under `services` defines a Kubernetes Deployment. The deployments template iterates over all entries and creates a Deployment + optional Service for each.
### Per-Service Structure
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `replicas` | int | yes | Number of pod replicas. Set to 0 by `pipelineEnabled: false` for pipeline services. |
| `image` | string | yes | Image name appended to `image.registry`. Also used as the Deployment name and pod label (`app: <image>`). |
| `command` | string | no | Shell command passed as `["sh", "-c", "<command>"]`. Omit for images with a built-in entrypoint (e.g., dashboard/nginx). |
| `tier` | string | yes | Service tier label (`stonks-oracle/tier`). One of: `api`, `frontend`, `processing`, `trading`, `orchestration`, `analytics`, `ingestion`. |
| `port` | int | no | Container port. When set, a Kubernetes Service is created mapping `port → port`. |
| `pipeline` | bool | no | If `true`, replicas are set to 0 when `pipelineEnabled` is `false`. |
| `secrets` | list(string) | no | List of Secret names to mount via `envFrom.secretRef`. |
| `resources` | object | yes | Kubernetes resource requests and limits (`cpu`, `memory`). |
| `probes.readiness` | object | no | HTTP readiness probe: `path`, `port`, `initialDelay`, `period`. |
| `probes.liveness` | object | no | HTTP liveness probe: `path`, `port`, `initialDelay`, `period`. |
### Service Definitions
#### scheduler
| Field | Value |
|-------|-------|
| `replicas` | `1` |
| `pipeline` | `true` |
| `image` | `scheduler` |
| `command` | `python -m services.scheduler.app` |
| `tier` | `orchestration` |
| `port` | — |
| `secrets` | `stonks-core-secrets` |
| `resources.requests` | cpu: 50m, memory: 64Mi |
| `resources.limits` | cpu: 200m, memory: 128Mi |
| `probes` | — |
The scheduler deployment has two init containers (not configurable via values):
1. **run-migrations** — applies all SQL files from `infra/migrations/*.sql` in sorted order.
2. **seed-if-empty** — runs `python -m services.symbol_registry.seed` if the `companies` table is empty.
#### symbolRegistry
| Field | Value |
|-------|-------|
| `replicas` | `1` |
| `image` | `symbol-registry` |
| `command` | `uvicorn services.symbol_registry.app:app --host 0.0.0.0 --port 8000` |
| `tier` | `api` |
| `port` | `8000` |
| `secrets` | `stonks-core-secrets` |
| `resources.requests` | cpu: 100m, memory: 128Mi |
| `resources.limits` | cpu: 500m, memory: 256Mi |
| `probes.readiness` | path: `/docs`, port: 8000, initialDelay: 5s, period: 10s |
| `probes.liveness` | path: `/docs`, port: 8000, initialDelay: 10s, period: 30s |
#### ingestion
| Field | Value |
|-------|-------|
| `replicas` | `2` |
| `pipeline` | `true` |
| `image` | `ingestion` |
| `command` | `python -m services.ingestion.worker` |
| `tier` | `ingestion` |
| `port` | — |
| `secrets` | `stonks-core-secrets`, `stonks-market-secrets`, `stonks-broker-secrets` |
| `resources.requests` | cpu: 100m, memory: 128Mi |
| `resources.limits` | cpu: 500m, memory: 256Mi |
#### parser
| Field | Value |
|-------|-------|
| `replicas` | `2` |
| `pipeline` | `true` |
| `image` | `parser` |
| `command` | `python -m services.parser.worker` |
| `tier` | `processing` |
| `port` | — |
| `secrets` | `stonks-core-secrets` |
| `resources.requests` | cpu: 100m, memory: 128Mi |
| `resources.limits` | cpu: 500m, memory: 256Mi |
#### extractor
| Field | Value |
|-------|-------|
| `replicas` | `1` |
| `pipeline` | `true` |
| `image` | `extractor` |
| `command` | `python -m services.extractor.main` |
| `tier` | `processing` |
| `port` | — |
| `secrets` | `stonks-core-secrets` |
| `resources.requests` | cpu: 200m, memory: 256Mi |
| `resources.limits` | cpu: 1, memory: 512Mi |
Single replica is recommended — the extractor is bottlenecked by the shared Ollama GPU.
#### aggregation
| Field | Value |
|-------|-------|
| `replicas` | `4` |
| `pipeline` | `true` |
| `image` | `aggregation` |
| `command` | `python -m services.aggregation.main` |
| `tier` | `processing` |
| `port` | — |
| `secrets` | `stonks-core-secrets` |
| `resources.requests` | cpu: 100m, memory: 128Mi |
| `resources.limits` | cpu: 500m, memory: 256Mi |
#### recommendation
| Field | Value |
|-------|-------|
| `replicas` | `1` |
| `pipeline` | `true` |
| `image` | `recommendation` |
| `command` | `python -m services.recommendation.main` |
| `tier` | `processing` |
| `port` | — |
| `secrets` | `stonks-core-secrets` |
| `resources.requests` | cpu: 100m, memory: 128Mi |
| `resources.limits` | cpu: 500m, memory: 256Mi |
#### tradingEngine
| Field | Value |
|-------|-------|
| `replicas` | `1` |
| `image` | `trading-engine` |
| `command` | `uvicorn services.trading.app:app --host 0.0.0.0 --port 8000` |
| `tier` | `trading` |
| `port` | `8000` |
| `secrets` | `stonks-core-secrets`, `stonks-broker-secrets`, `stonks-gmail-secrets` |
| `resources.requests` | cpu: 100m, memory: 256Mi |
| `resources.limits` | cpu: 500m, memory: 512Mi |
| `probes.readiness` | path: `/ready`, port: 8000, initialDelay: 5s, period: 10s |
| `probes.liveness` | path: `/health`, port: 8000, initialDelay: 10s, period: 30s |
#### riskEngine
| Field | Value |
|-------|-------|
| `replicas` | `1` |
| `image` | `risk` |
| `command` | `uvicorn services.risk.app:app --host 0.0.0.0 --port 8000` |
| `tier` | `trading` |
| `port` | `8000` |
| `secrets` | `stonks-core-secrets`, `stonks-broker-secrets` |
| `resources.requests` | cpu: 100m, memory: 128Mi |
| `resources.limits` | cpu: 500m, memory: 256Mi |
#### brokerAdapter
| Field | Value |
|-------|-------|
| `replicas` | `1` |
| `pipeline` | `true` |
| `image` | `broker-adapter` |
| `command` | `python -m services.adapters.broker_service` |
| `tier` | `trading` |
| `port` | — |
| `secrets` | `stonks-core-secrets`, `stonks-broker-secrets` |
| `resources.requests` | cpu: 50m, memory: 64Mi |
| `resources.limits` | cpu: 200m, memory: 128Mi |
#### lakePublisher
| Field | Value |
|-------|-------|
| `replicas` | `1` |
| `pipeline` | `true` |
| `image` | `lake-publisher` |
| `command` | `python -m services.lake_publisher.jobs` |
| `tier` | `analytics` |
| `port` | — |
| `secrets` | `stonks-core-secrets` |
| `resources.requests` | cpu: 100m, memory: 128Mi |
| `resources.limits` | cpu: 500m, memory: 256Mi |
#### queryApi
| Field | Value |
|-------|-------|
| `replicas` | `1` |
| `image` | `query-api` |
| `command` | `uvicorn services.api.app:app --host 0.0.0.0 --port 8000` |
| `tier` | `api` |
| `port` | `8000` |
| `secrets` | `stonks-core-secrets` |
| `resources.requests` | cpu: 100m, memory: 128Mi |
| `resources.limits` | cpu: 500m, memory: 256Mi |
| `probes.readiness` | path: `/docs`, port: 8000, initialDelay: 5s, period: 10s |
#### dashboard
| Field | Value |
|-------|-------|
| `replicas` | `1` |
| `image` | `dashboard` |
| `command` | — (nginx built-in entrypoint) |
| `tier` | `frontend` |
| `port` | `8080` |
| `secrets` | — |
| `resources.requests` | cpu: 50m, memory: 64Mi |
| `resources.limits` | cpu: 200m, memory: 128Mi |
| `probes.readiness` | path: `/`, port: 8080, initialDelay: 3s, period: 10s |
| `probes.liveness` | path: `/`, port: 8080, initialDelay: 5s, period: 30s |
---
## `config` — ConfigMap Environment Variables
All keys under `config` are rendered into a Kubernetes ConfigMap named `stonks-config` and injected into every service pod via `envFrom.configMapRef`. Values are strings.
### Database
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `config.POSTGRES_HOST` | string | `postgresql-rw.postgresql-service.svc.cluster.local` | PostgreSQL hostname. Points to the CloudNativePG read-write service. |
| `config.POSTGRES_PORT` | string | `5432` | PostgreSQL port. |
| `config.POSTGRES_DB` | string | `stonks` | Database name. Override per stage (e.g., `stonks_beta`, `stonks_paper`). |
| `config.POSTGRES_USER` | string | `stonks` | Database user. Override per stage. |
| `config.REDIS_HOST` | string | `redis-master.redis-service.svc.cluster.local` | Redis hostname. |
| `config.REDIS_PORT` | string | `6379` | Redis port. |
| `config.REDIS_DB` | string | `0` | Redis database index. Use different indices per stage to isolate keys (beta: `1`, paper: `2`). |
### Object Storage
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `config.MINIO_ENDPOINT` | string | `minio.minio-service.svc.cluster.local:80` | MinIO API endpoint (host:port). |
| `config.MINIO_SECURE` | string | `false` | Use HTTPS for MinIO connections. Set to `true` if MinIO has TLS. |
### LLM / Ollama
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `config.OLLAMA_BASE_URL` | string | `""` (empty) | Ollama API base URL. Set to the cluster-internal or external Ollama endpoint. |
| `config.OLLAMA_MODEL` | string | `qwen3.5:9b-fast` | Default LLM model for extraction and classification agents. |
| `config.OLLAMA_TIMEOUT` | string | `240` | Request timeout in seconds for Ollama API calls. |
| `config.OLLAMA_MAX_RETRIES` | string | `2` | Maximum retry attempts for failed Ollama requests. |
| `config.OLLAMA_RETRY_BASE_DELAY` | string | `1.0` | Base delay in seconds for exponential backoff on Ollama retries. |
| `config.OLLAMA_RETRY_MAX_DELAY` | string | `10.0` | Maximum delay cap in seconds for Ollama retry backoff. |
| `config.OLLAMA_RETRY_BACKOFF_MULTIPLIER` | string | `2.0` | Multiplier for exponential backoff between Ollama retries. |
### Analytics / Trino
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `config.TRINO_HOST` | string | `trino.stonks-oracle.svc.cluster.local` | Trino coordinator hostname. |
| `config.TRINO_PORT` | string | `8080` | Trino coordinator port. |
| `config.TRINO_CATALOG` | string | `lakehouse` | Default Trino catalog for Hive-based queries. |
| `config.TRINO_SCHEMA` | string | `stonks` | Default Trino schema. |
| `config.TRINO_ICEBERG_CATALOG` | string | `iceberg` | Trino catalog for Iceberg table queries. |
### Broker / Trading
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `config.BROKER_MODE` | string | `paper` | Broker execution mode. `paper` for simulated trading, `live` for real orders. |
| `config.BROKER_PROVIDER` | string | `""` (empty) | Broker provider name (e.g., `alpaca`). |
| `config.MARKET_DATA_BASE_URL` | string | `""` (empty) | Market data API base URL (e.g., `https://api.polygon.io`). |
| `config.MARKET_DATA_PROVIDER` | string | `polygon` | Market data provider identifier. |
| `config.TRADING_ENABLED` | string | `true` | Master toggle for the trading engine. Set to `false` to disable order submission. |
| `config.TRADING_RISK_TIER` | string | `moderate` | Default risk tier for position sizing. Options: `conservative`, `moderate`, `aggressive`. |
| `config.TRADING_ABSOLUTE_POSITION_CAP` | string | `10000.0` | Maximum dollar value per position. |
| `config.TRADING_MAX_OPEN_POSITIONS` | string | `10` | Maximum number of concurrent open positions. |
### Data Retention
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `config.RETENTION_RAW_MARKET_DAYS` | string | `90` | Days to retain raw market data before cleanup. |
| `config.RETENTION_RAW_NEWS_DAYS` | string | `180` | Days to retain raw news articles. |
| `config.RETENTION_RAW_FILINGS_DAYS` | string | `365` | Days to retain raw SEC filings. |
| `config.RETENTION_NORMALIZED_DAYS` | string | `180` | Days to retain normalized/parsed documents. |
| `config.RETENTION_LLM_PROMPTS_DAYS` | string | `365` | Days to retain LLM prompt logs. |
| `config.RETENTION_LLM_RESULTS_DAYS` | string | `365` | Days to retain LLM extraction results. |
| `config.RETENTION_LAKEHOUSE_DAYS` | string | `730` | Days to retain lakehouse fact tables. |
| `config.RETENTION_AUDIT_DAYS` | string | `730` | Days to retain audit trail events. |
| `config.RETENTION_CLEANUP_INTERVAL_HOURS` | string | `24` | Hours between retention cleanup runs. |
| `config.RETENTION_BATCH_SIZE` | string | `1000` | Number of rows deleted per cleanup batch. |
### Logging and Deployment
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `config.LOG_LEVEL` | string | `INFO` | Python logging level. Options: `DEBUG`, `INFO`, `WARNING`, `ERROR`. |
| `config.JSON_LOGS` | string | `true` | Emit structured JSON logs when `true`. |
| `config.DEPLOY_STAGE` | string | `""` (empty) | Deployment stage identifier. Used to isolate Redis keys and MinIO buckets per stage (e.g., `beta`, `paper`). |
| `config.TZ` | string | `America/Los_Angeles` | Container timezone. Affects log timestamps and any time-aware formatting. The frontend uses the browser's local timezone for display. |
### Alerting
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `config.ALERT_SOURCE_FAILURE_THRESHOLD` | string | `3` | Number of consecutive source failures before firing an alert. |
| `config.ALERT_SOURCE_FAILURE_WINDOW_HOURS` | string | `6` | Time window (hours) for evaluating source failure count. |
| `config.ALERT_SCHEMA_FAILURE_RATE_THRESHOLD` | string | `0.3` | Schema validation failure rate (0.01.0) that triggers an alert. |
| `config.ALERT_SCHEMA_FAILURE_WINDOW_HOURS` | string | `1` | Time window (hours) for evaluating schema failure rate. |
| `config.ALERT_LAKE_LAG_THRESHOLD_MINUTES` | string | `60` | Minutes of lakehouse publish lag before alerting. |
| `config.ALERT_BROKER_ERROR_THRESHOLD` | string | `3` | Number of broker errors before firing an alert. |
| `config.ALERT_BROKER_ERROR_WINDOW_HOURS` | string | `1` | Time window (hours) for evaluating broker error count. |
| `config.ALERT_CHECK_INTERVAL_SECONDS` | string | `120` | Seconds between alert evaluation cycles. |
---
## `secrets` — Kubernetes Secrets
Secrets are rendered into five Kubernetes Secret objects. In the base `values.yaml`, all secret values default to empty strings. Inject real values at deploy time using `--set` flags or a values override file.
### Secret Objects
| Secret Name | Values Key | Consumed By |
|-------------|-----------|-------------|
| `stonks-core-secrets` | `secrets.core` | All services |
| `stonks-broker-secrets` | `secrets.broker` | ingestion, trading-engine, risk-engine, broker-adapter |
| `stonks-market-secrets` | `secrets.market` | ingestion |
| `stonks-gmail-secrets` | `secrets.gmail` | trading-engine |
| `stonks-dashboard-secrets` | `secrets.dashboard` | superset |
### `secrets.core`
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `POSTGRES_PASSWORD` | string | `""` | PostgreSQL password. |
| `MINIO_ACCESS_KEY` | string | `""` | MinIO access key (AWS-style). |
| `MINIO_SECRET_KEY` | string | `""` | MinIO secret key. |
| `REDIS_PASSWORD` | string | `""` | Redis authentication password. |
### `secrets.broker`
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `BROKER_API_KEY` | string | `""` | Broker API key (e.g., Alpaca paper trading key). |
| `BROKER_API_SECRET` | string | `""` | Broker API secret. |
| `BROKER_BASE_URL` | string | `""` | Broker API base URL (e.g., `https://paper-api.alpaca.markets`). |
### `secrets.market`
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `MARKET_DATA_API_KEY` | string | `""` | Market data provider API key (e.g., Polygon.io). |
### `secrets.gmail`
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `GMAIL_SENDER` | string | `celes@celestium.life` | Gmail sender address for trading notifications. |
| `GMAIL_RECIPIENT` | string | `celes@celestium.life` | Gmail recipient address for trading notifications. |
| `GMAIL_APP_PASSWORD` | string | `""` | Gmail app password for SMTP authentication. |
### `secrets.dashboard`
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `SUPERSET_SECRET_KEY` | string | `""` | Flask secret key for Superset session encryption. |
| `SUPERSET_ADMIN_PASSWORD` | string | `""` | Superset admin user password. |
### Injecting Secrets at Deploy Time
```bash
helm upgrade --install stonks-oracle infra/helm/stonks-oracle \
-n stonks-oracle \
--set secrets.core.POSTGRES_PASSWORD="<password>" \
--set secrets.core.MINIO_ACCESS_KEY="<key>" \
--set secrets.core.MINIO_SECRET_KEY="<secret>" \
--set secrets.core.REDIS_PASSWORD="<password>" \
--set secrets.broker.BROKER_API_KEY="<key>" \
--set secrets.broker.BROKER_API_SECRET="<secret>" \
--set secrets.broker.BROKER_BASE_URL="https://paper-api.alpaca.markets" \
--set secrets.market.MARKET_DATA_API_KEY="<key>" \
--set secrets.gmail.GMAIL_APP_PASSWORD="<password>" \
--set secrets.dashboard.SUPERSET_SECRET_KEY="<key>" \
--set secrets.dashboard.SUPERSET_ADMIN_PASSWORD="<password>"
```
---
## `ingress` — Ingress Configuration
Controls Traefik Ingress resources with TLS via cert-manager.
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `ingress.enabled` | bool | `true` | Create Ingress resources. Set to `false` for port-forward-only access. |
| `ingress.className` | string | `traefik` | Kubernetes IngressClass name. |
| `ingress.clusterIssuer` | string | `ca-issuer` | cert-manager ClusterIssuer for TLS certificates. |
### Host Mappings
| Key | Default | Routes To | Port |
|-----|---------|-----------|------|
| `ingress.hosts.queryApi` | `stonks-api.celestium.life` | query-api Service | 8000 |
| `ingress.hosts.symbolRegistry` | `stonks-registry.celestium.life` | symbol-registry Service | 8000 |
| `ingress.hosts.dashboard` | `stonks.celestium.life` | dashboard Service | 8080 |
| `ingress.hosts.superset` | `stonks-dash.celestium.life` | superset Service | 8088 |
| `ingress.hosts.trino` | `stonks-trino.celestium.life` | trino Service | 8080 |
| `ingress.hosts.tradingEngine` | `stonks-trading.celestium.life` | trading-engine Service | 8000 |
Setting `superset` or `trino` host to an empty string (`""`) disables that Ingress resource (the template uses a conditional check).
Each Ingress resource gets a dedicated TLS secret (e.g., `stonks-api-tls`, `stonks-registry-tls`) automatically provisioned by cert-manager.
---
## Analytics Stack — Trino, Hive Metastore, Superset
The analytics stack provides SQL-based querying over the lakehouse data stored in MinIO. Each component can be independently enabled or disabled.
### `trino`
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `trino.enabled` | bool | `true` | Deploy the Trino coordinator. |
| `trino.resources.requests.cpu` | string | `500m` | CPU request. |
| `trino.resources.requests.memory` | string | `1Gi` | Memory request. |
| `trino.resources.limits.cpu` | string | `2` | CPU limit. |
| `trino.resources.limits.memory` | string | `4Gi` | Memory limit. |
When enabled, Trino deploys with two auto-configured catalogs:
- **`lakehouse`** — Hive connector for Parquet fact tables in MinIO.
- **`iceberg`** — Iceberg connector for Iceberg-format tables.
Both catalogs connect to the Hive Metastore for schema metadata and to MinIO for data via S3A. MinIO credentials are read from `stonks-core-secrets`.
### `hiveMetastore`
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `hiveMetastore.enabled` | bool | `true` | Deploy the Hive Metastore. |
| `hiveMetastore.storageSize` | string | `1Gi` | PersistentVolumeClaim size for the embedded Derby metastore database. |
| `hiveMetastore.resources.requests.cpu` | string | `200m` | CPU request. |
| `hiveMetastore.resources.requests.memory` | string | `512Mi` | Memory request. |
| `hiveMetastore.resources.limits.cpu` | string | `1` | CPU limit. |
| `hiveMetastore.resources.limits.memory` | string | `1Gi` | Memory limit. |
Uses `apache/hive:4.0.0` with an embedded Derby database. The Thrift metastore listens on port 9083. MinIO credentials are injected from `stonks-core-secrets` via an init container that generates `core-site.xml` and `metastore-site.xml`.
### `superset`
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `superset.enabled` | bool | `true` | Deploy Apache Superset. |
| `superset.storageSize` | string | `2Gi` | PersistentVolumeClaim size for Superset home directory. |
| `superset.resources.requests.cpu` | string | `200m` | CPU request. |
| `superset.resources.requests.memory` | string | `512Mi` | Memory request. |
| `superset.resources.limits.cpu` | string | `1` | CPU limit. |
| `superset.resources.limits.memory` | string | `2Gi` | Memory limit. |
Uses a custom image (`registry.celestium.life/stonks-oracle/superset`) with Trino and psycopg2 drivers pre-installed. Superset's metadata database is PostgreSQL (same cluster instance). Redis is used for caching. Credentials come from `stonks-core-secrets` and `stonks-dashboard-secrets`.
Superset listens on port 8088 with a readiness probe at `/health`.
### Disabling the Analytics Stack
To disable the entire analytics stack (e.g., in beta environments):
```yaml
trino:
enabled: false
hiveMetastore:
enabled: false
superset:
enabled: false
```
---
## `networkPolicies` — Network Policy Configuration
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `networkPolicies.enabled` | bool | `true` | Deploy NetworkPolicy resources. |
When enabled, the chart creates a **default-deny-ingress** policy that blocks all inbound traffic to every pod in the namespace. Individual allow policies are then created for services that need ingress:
| Policy | Target Pod | Allowed Sources | Port |
|--------|-----------|-----------------|------|
| `allow-query-api-ingress` | `query-api` | kube-system (Traefik), dashboard | 8000 |
| `allow-symbol-registry-ingress` | `symbol-registry` | kube-system (Traefik), dashboard | 8000 |
| `allow-risk-engine-ingress` | `risk` | broker-adapter, query-api, dashboard | 8000 |
| `allow-trading-engine-ingress` | `trading-engine` | query-api, dashboard, kube-system (Traefik) | 8000 |
| `allow-superset-ingress` | `superset` | kube-system (Traefik) | 8088 |
| `allow-trino-ingress` | `trino` | superset, query-api, kube-system (Traefik) | 8080 |
| `allow-hive-metastore-ingress` | `hive-metastore` | trino, lake-publisher | 9083 |
| `allow-dashboard-ingress` | `dashboard` | kube-system (Traefik) | 8080 |
| `deny-broker-adapter-ingress` | `broker-adapter` | (none — explicit deny) | — |
The trading-engine also has egress rules allowing outbound connections to PostgreSQL (5432), Redis (6379), HTTPS (443), SMTP (587), and DNS (53).
Pipeline workers (scheduler, ingestion, parser, extractor, aggregation, recommendation, lake-publisher) have no explicit ingress allow policies — they rely on the default-deny and communicate only via outbound connections to Redis queues and PostgreSQL.
---
## Value Override Files
The chart ships with two override files for staged deployments. ArgoCD or Kargo applies these during promotion.
### `values-beta.yaml` — Beta / Integration Testing
**Purpose**: Integration testing environment deployed to `stonks-oracle-beta` namespace. Shares infrastructure with paper but uses isolated database (`stonks_beta`), Redis DB index (`1`), and separate ingress hostnames.
Key overrides:
| Key | Beta Value | Reason |
|-----|-----------|--------|
| `pipelineEnabled` | `true` | Services deployed (ArgoCD health checks), but pipeline defaults to OFF via `PIPELINE_DEFAULT_OFF`. |
| `config.DEPLOY_STAGE` | `beta` | Isolates Redis keys (`stonks:beta:*`) and MinIO buckets (`beta-stonks-*`). |
| `config.POSTGRES_DB` | `stonks_beta` | Separate database for beta data. |
| `config.REDIS_DB` | `1` | Separate Redis DB index. |
| `config.LOG_LEVEL` | `DEBUG` | Verbose logging for debugging. |
| `config.TRADING_ENABLED` | `false` | Safety net — no order submission in beta. |
| `config.PIPELINE_DEFAULT_OFF` | `true` | Scheduler won't enqueue jobs unless explicitly enabled. |
| `config.OLLAMA_MODEL` | `qwen3.6` | May use a different model version for testing. |
| `trino.enabled` | `false` | Analytics stack disabled in beta. |
| `hiveMetastore.enabled` | `false` | Analytics stack disabled in beta. |
| `superset.enabled` | `false` | Analytics stack disabled in beta. |
Beta ingress hostnames:
| Service | Hostname |
|---------|----------|
| Query API | `stonks-api-beta.celestium.life` |
| Symbol Registry | `stonks-registry-beta.celestium.life` |
| Dashboard | `stonks-beta.celestium.life` |
| Trading Engine | `stonks-trading-beta.celestium.life` |
| Superset | (disabled) |
| Trino | (disabled) |
### `values-paper.yaml` — Paper Trading
**Purpose**: Paper trading environment with real market data but simulated order execution via Alpaca's paper trading API. Deployed to the main `stonks-oracle` namespace.
Key overrides:
| Key | Paper Value | Reason |
|-----|-----------|--------|
| `config.BROKER_MODE` | `paper` | Simulated order execution. |
| `config.BROKER_PROVIDER` | `alpaca` | Alpaca paper trading API. |
| `config.TRADING_ENABLED` | `true` | Trading engine active. |
| `config.POSTGRES_DB` | `stonks_paper` | Separate database for paper trading data. |
| `config.POSTGRES_USER` | `stonks_paper` | Separate database user. |
| `config.REDIS_DB` | `2` | Separate Redis DB index. |
| `config.DEPLOY_STAGE` | `paper` | Stage identifier. |
| `config.LOG_LEVEL` | `INFO` | Standard logging. |
| `services.extractor.replicas` | `1` | Single replica (GPU bottleneck). |
Paper ingress hostnames:
| Service | Hostname |
|---------|----------|
| Query API | `stonks-paper-api.celestium.life` |
| Symbol Registry | `stonks-paper-registry.celestium.life` |
| Dashboard | `stonks-paper.celestium.life` |
| Superset | `stonks-paper-dash.celestium.life` |
| Trino | `stonks-paper-trino.celestium.life` |
| Trading Engine | `stonks-paper-trading.celestium.life` |
### Deployment Stage Progression
```
values-beta.yaml values-paper.yaml values.yaml (base)
Beta → Paper Trading → Production
Integration Simulated orders Live trading
testing Real market data Real orders
Pipeline OFF Pipeline ON Pipeline ON
Trading OFF Trading ON Trading ON
Analytics OFF Analytics ON Analytics ON
```
Promotion between stages is managed by Kargo/ArgoCD. CI sets the image tag, and the promotion pipeline applies the appropriate values file.
@@ -0,0 +1,130 @@
# Page 1 — Data Ingestion and Preparation
Every signal that Stonks Oracle eventually acts on begins its life as raw data pulled from an external source. Before any AI agent can extract structured intelligence, before any trend can accumulate, and before any trade can be placed, the platform must first discover new content, fetch it reliably, eliminate duplicates, store the raw artifacts for audit, and normalize the text into a form suitable for downstream processing. This page traces that journey from external API to parser output, covering the Scheduler, Ingestion Worker, deduplication layer, raw storage, and Parser in detail.
For a visual overview of the full flow described here, see the [Ingestion to Extraction Flow diagram](diagrams/ingestion-to-extraction-flow.md).
---
## Four Categories of Input Data
Stonks Oracle tracks 50 companies across 10 sectors, and it draws intelligence from four distinct categories of external data. Each category has its own adapter, its own API conventions, and its own scheduling cadence, but all of them feed into the same ingestion pipeline.
The first category is **company news**, sourced from the Polygon.io ticker news endpoint (`/v2/reference/news`). The `PolygonNewsAdapter` in `services/adapters/news_adapter.py` fetches articles linked to a specific ticker, returning structured results that include title, publisher, article URL, description, keywords, and publication timestamp. Each request can return up to 1,000 articles, though the default limit is 20 per fetch. The adapter tracks the most recent `published_utc` value and uses it on subsequent fetches to avoid re-retrieving articles the system has already seen.
The second category is **SEC filings**, sourced from the SEC EDGAR full-text search system (EFTS). The `SECEdgarAdapter` in `services/adapters/filings_adapter.py` queries the `/LATEST/search-index` endpoint for 8-K, 10-Q, 10-K, and other form types associated with a company's ticker or CIK number. Unlike the Polygon endpoints, EDGAR is a public API that requires no key — only a descriptive `User-Agent` header per the SEC's fair-access policy. The adapter deduplicates results by accession number (`adsh`), filters out non-primary documents like XML fragments and graphics, and constructs the SEC EDGAR filing index URL for each hit so downstream services can fetch the full document.
The third category is **market data**, also sourced from Polygon.io. The `PolygonMarketAdapter` in `services/adapters/market_adapter.py` supports multiple endpoints: previous-day aggregate bars (`/v2/aggs/ticker/{ticker}/prev`), range bars for custom date windows, intraday hourly bars, grouped daily bars that return data for all tickers in a single call (`/v2/aggs/grouped/locale/us/market/stocks/{date}`), and ticker detail lookups. Market data follows a different path than textual content — it does not pass through the Parser or Extractor, since the structured numeric data is already in a usable form.
The fourth category is **macro and geopolitical news**, fetched by the `MacroNewsAdapter` in `services/adapters/macro_news_adapter.py`. Unlike the other three categories, macro news is not company-specific. These sources have `source_type='macro_news'` in the `sources` database table and may have a `NULL` `company_id`. The adapter fetches from a configurable HTTP endpoint (typically the Polygon news API filtered for broad market topics) and returns articles that describe global events — trade policy shifts, central bank decisions, geopolitical conflicts — rather than company-specific developments. Macro news articles are eventually classified by the Global Event Classifier agent and routed through a separate queue, as described in [Page 2](02-ai-agent-processing-and-extraction.md).
All four adapter classes inherit from `BaseAdapter` defined in `services/adapters/base.py` and return an `AdapterResult` dataclass containing the raw payload bytes, a SHA-256 content hash, a list of parsed item dicts, HTTP metadata (status code, response time), and an error field that is `None` on success. This uniform interface allows the Ingestion Worker to handle all source types through a single dispatch mechanism.
---
## The Scheduler: Orchestrating Ingestion Cycles
The Scheduler (`services/scheduler/app.py`) is the heartbeat of the ingestion pipeline. It runs a continuous loop that ticks every 15 seconds (`SCHEDULER_TICK = 15`), and on each tick it evaluates which sources are due for their next fetch. The Scheduler does not fetch data itself — it enqueues jobs onto the `stonks:queue:ingestion` Redis list for the Ingestion Worker to process.
Each source type has a default polling cadence defined in the `DEFAULT_CADENCES` dictionary:
| Source Type | Default Cadence |
|---------------|-----------------|
| `market_api` | 300 seconds |
| `news_api` | 300 seconds |
| `filings_api` | 3,600 seconds |
| `macro_news` | 600 seconds |
| `web_scrape` | 1,800 seconds |
| `broker` | 30 seconds |
Individual sources can override their cadence via the `polling_interval_seconds` field in their `config` JSONB column in the `sources` table. The `get_cadence_for_source()` function checks for this override first, falling back to the default if none is set, and enforces a minimum interval of 10 seconds.
The Scheduler determines whether a source is due by calling `is_source_due()`, which considers several conditions. If a source has never run before (no entry in the `ingestion_runs` table), it is immediately due. If the last run failed, the Scheduler respects an exponential backoff computed by `compute_backoff()`: the delay starts at 60 seconds (`DEFAULT_BACKOFF_BASE`) and doubles with each retry up to a maximum of 3,600 seconds (`MAX_BACKOFF`). If a source has failed 10 consecutive times (`MAX_RETRY_COUNT`), the Scheduler stops scheduling it entirely until an operator manually resets the retry state. If the last run is still marked as `running`, the source is skipped to prevent double-scheduling. Otherwise, the Scheduler checks whether enough time has elapsed since the last completed run based on the source's cadence.
Rate limiting adds another layer of protection. The `check_rate_limit()` function enforces two constraints. First, each source type has a per-type limit defined in `DEFAULT_RATE_LIMITS` — for example, `market_api` and `news_api` are each capped at 20 requests per minute, while `filings_api` and `macro_news` are capped at 10. Second, because `market_api` and `news_api` both use the same Polygon.io API key, a global Polygon rate limit of 45 requests per minute (`POLYGON_GLOBAL_RATE_LIMIT`) is enforced across both types combined. Rate limit state is tracked in Redis using keys of the form `stonks:ratelimit:{source_type}:{window}`, where the window is a minute-granularity timestamp. If a source type exceeds its limit, the Scheduler logs a warning and skips that source for the current tick.
The Scheduler handles three categories of sources in each cycle. First, it fetches all active company-specific sources (excluding `macro_news`) by joining the `sources` and `companies` tables. Second, it fetches active macro news sources separately, since these may not have a `company_id`. Third, it fetches global market sources — those with `source_type='market_api'` and `company_id IS NULL` — which represent endpoints like the grouped daily bars that return data for all tickers in a single API call. For intraday bar sources, the Scheduler expands a single global source into per-ticker jobs for every active company.
Each enqueued job payload includes the `source_id`, `company_id`, `ticker`, `legal_name`, `source_type`, `source_name`, `config`, `credibility_score`, a list of company `aliases` (fetched from the `company_aliases` table), and a `scheduled_at` timestamp. The job is pushed onto `stonks:queue:ingestion` via Redis `RPUSH`.
Beyond scheduling, the Scheduler also performs periodic maintenance. Every ~20 cycles (~5 minutes), it runs `recover_stale_documents()` to re-enqueue documents that have been stuck in `parsed` status for longer than 240 minutes — a safety net for cases where Redis loses queue entries due to pod restarts or OOM events. Every ~40 cycles (~10 minutes), it runs `retry_failed_extractions()` to give documents in `extraction_failed` status another chance, resetting them to `parsed` and deleting the failed `document_intelligence` row so the Extractor treats them as fresh. Every ~100 cycles (~25 minutes), it runs `cleanup_all_tables()` to enforce retention policies across tables like `competitive_signal_records` (30 days), `ingestion_runs` (14 days), and `trading_decisions` (90 days).
For more detail on the Scheduler's configuration and operational behavior, see the [Services Reference](../services.md).
---
## The Ingestion Worker: Adapter Dispatch and Persistence
The Ingestion Worker (`services/ingestion/worker.py`) is a long-running process that continuously pops jobs from the `stonks:queue:ingestion` Redis list and processes them. On startup, it initializes one instance of each adapter class and stores them in a dispatch dictionary keyed by `source_type`:
```
adapters = {
"market_api": PolygonMarketAdapter(...),
"news_api": PolygonNewsAdapter(...),
"filings_api": SECEdgarAdapter(),
"web_scrape": WebScrapeAdapter(),
"broker": AlpacaBrokerAdapter(...),
"macro_news": MacroNewsAdapter(...),
}
```
When a job arrives, the `process_job()` function looks up the appropriate adapter by `source_type` and calls its `fetch()` method with the ticker and source config. Before fetching, it records a new row in the `ingestion_runs` table with status `running`. If the adapter returns an error, the worker calls `record_retrieval_failure()` to update the run status and increment the source's retry counter with exponential backoff timing.
On a successful fetch, the worker performs several steps in sequence. First, it uploads the raw payload to MinIO via `upload_raw_artifact()` in `services/shared/storage.py`. The target bucket is determined by the source type through the `SOURCE_BUCKET_MAP`: `market_api` payloads go to `stonks-raw-market`, `news_api` and `macro_news` payloads go to `stonks-raw-news`, and `filings_api` payloads go to `stonks-raw-filings`. Objects are stored under a path that encodes the source type, ticker, date hierarchy, and document ID — for example, `news_api/AAPL/2025/01/15/{run_id}/raw.json`.
---
## Content Deduplication via Redis
After storing the raw artifact, the Ingestion Worker checks for duplicate content. Deduplication operates at two levels.
At the payload level, the worker checks the overall `content_hash` (a SHA-256 digest of the raw API response) against Redis. The key pattern is `stonks:dedupe:{content_hash}` with a 24-hour TTL (86,400 seconds). If the hash is already present, the entire payload is skipped — the `ingestion_runs` row is marked as completed with `items_new=0`, and no downstream jobs are enqueued. If the hash is new, the worker sets the marker in Redis so future fetches of identical content are caught.
At the individual item level, for source types other than `market_api` and `broker`, the worker calls `dedupe_items()` from `services/shared/dedupe.py`. This function checks each item against a layered deduplication strategy. The fast path checks Redis for both content-hash markers (`stonks:dedupe:{hash}`) and canonical-URL markers (`stonks:dedupe:url:{url_hash}`), both with 24-hour TTLs. If the Redis check misses, the function falls back to PostgreSQL, querying the `documents` table by `content_hash` or `canonical_url` for durable cross-source matching. When a duplicate is found through the PostgreSQL fallback, the function warms the Redis cache so subsequent checks are fast.
Items identified as duplicates are not discarded entirely. If the duplicate document was originally ingested for a different company, the worker creates a cross-source mention link in the `document_company_mentions` table via `persist_document_company_mention()`. This ensures that a news article mentioning both Apple and Microsoft is linked to both companies even if it was first ingested through Apple's news source.
New (non-duplicate) items are persisted to PostgreSQL through `persist_ingestion_items()` in `services/shared/metadata.py`, which inserts rows into the `documents` table and records company mentions in `document_company_mentions`. Each new document ID is then pushed onto `stonks:queue:parsing` for the Parser to process. After persistence, the worker calls `mark_as_seen()` to set Redis dedupe markers for both the content hash and canonical URL of each new item, ensuring that the next fetch cycle's deduplication checks are fast.
On successful completion, the worker updates the `ingestion_runs` row with the final counts (`items_fetched`, `items_new`) and calls `reset_source_retry_state()` to clear any accumulated backoff from previous failures. For news-type sources (`news_api` and `macro_news`), the worker also updates the source's `config` JSONB column with the latest `published_utc` value, so the next fetch only retrieves newer articles.
---
## The Parser: Normalization, Quality Scoring, and Routing
Documents that pass through ingestion arrive on the `stonks:queue:parsing` Redis list as JSON payloads containing a `document_id`, `ticker`, and `source_type`. The Parser Worker (`services/parser/worker.py`) pops these jobs and transforms raw HTML or text into normalized, quality-scored documents ready for AI extraction.
The parsing pipeline begins with HTML fetching. If the document has a URL (looked up from the `documents` table if not present in the job payload), the worker calls `fetch_html()` to retrieve the page content. SEC EDGAR URLs receive a specialized `User-Agent` header to comply with the SEC's fair-access policy. The raw HTML is then passed to `parse_html()` in `services/parser/html_parser.py`, which runs a multi-stage extraction pipeline.
The HTML parser first strips non-content tags — `script`, `style`, `nav`, `footer`, `header`, `aside`, `iframe`, and others — and removes boilerplate containers identified by CSS class or ID patterns (sidebars, ad slots, newsletter signups, social share bars, and similar UI elements). It then searches for the article body using a priority list of semantic selectors (`article`, `[role='main']`, `.article-body`, `.post-content`, and others). If no semantic match is found, it falls back to text-density scoring across candidate `div`, `section`, and `td` elements, selecting the block with the highest composite score based on text density, link density, paragraph count, and word count. The extracted text undergoes further cleaning: regex-based removal of residual boilerplate phrases (copyright notices, "subscribe to our newsletter" prompts, "share this article" fragments), removal of short orphan lines that are likely UI fragments, detection and collapse of repeated template blocks, and whitespace normalization.
Metadata extraction pulls the document title (from `og:title` or `<title>`), author, publisher (from `og:site_name` or hostname), publication date (from `article:published_time` or JSON-LD `datePublished`), canonical URL, language, description, and keywords from the HTML head elements.
If the parsed body text is shorter than 500 characters, the worker attempts to enrich it by reading the raw API payload from MinIO and extracting the Polygon article description, keywords, and author fields for the matching article. This enrichment step ensures that even articles with minimal scrapeable HTML still have enough textual content for meaningful AI extraction.
Quality scoring is performed by `score_parse_quality()` in `services/parser/html_parser.py`, which evaluates six weighted signals to produce a composite score between 0 and 0.95:
| Signal | Weight | What It Measures |
|--------------------|--------|-----------------------------------------------------------------|
| `word_count` | 0.30 | Length of extracted text (thresholds at 20, 50, 150, 300 words) |
| `body_found` | 0.20 | Whether a semantic article body element was located |
| `diversity` | 0.15 | Vocabulary richness (unique words / total words) |
| `sentence` | 0.15 | Presence of proper sentence structure (terminal punctuation) |
| `paragraph` | 0.10 | Multi-paragraph structure (blocks separated by blank lines) |
| `metadata` | 0.10 | Presence of title, author, publisher, and publication date |
The composite score maps to a confidence label: scores below 0.35 are labeled `low`, scores between 0.35 and 0.65 are `medium`, and scores 0.65 and above are `high`. Documents with `low` confidence are marked with status `low_quality` in the `documents` table and are not enqueued for extraction — they are effectively filtered out of the pipeline at this stage.
Company mention detection runs next. The worker fetches all known aliases from the `company_aliases` table (plus tickers and legal names from the `companies` table) and calls `detect_company_mentions()` in `services/parser/html_parser.py`. The matching strategy varies by alias length: one-to-two character aliases use case-sensitive word-boundary matching to avoid false positives (the letter "A" should not match every occurrence of the word "a"), three-to-four character aliases use case-insensitive word-boundary matching (standard ticker format), and aliases of five or more characters use case-insensitive substring matching (company names and brands). Confidence scores vary by alias type: ticker matches receive 0.9, legal name matches 0.85, general aliases 0.7, and brand matches 0.6. Multiple alias hits for the same company are deduplicated, keeping the highest-confidence match and summing match counts. Detected mentions are persisted to the `document_company_mentions` table.
The normalized text and a structured parser output JSON (containing all metadata, quality signals, warnings, outbound links, tags, and mentions) are uploaded to the `stonks-normalized` MinIO bucket. The `documents` row is updated with the normalized storage reference, parser output reference, quality score, and confidence level.
Finally, the Parser makes a routing decision. If the document's `document_type` is `macro_event`, it is pushed onto `stonks:queue:macro_classification` for the Global Event Classifier agent. All other documents are pushed onto `stonks:queue:extraction` for the Document Intelligence Extractor agent. Both queues feed into the Extractor service described in [Page 2](02-ai-agent-processing-and-extraction.md). The job payload includes the `document_id`, `ticker`, and the first 32,000 characters of the normalized text, giving the downstream agent immediate access to the content without needing to fetch it from MinIO.
For additional detail on queue topology and data store layout, see the [Data Pipeline Architecture](../architecture-data-pipeline.md) documentation.
---
## What Comes Next
At this point, raw data has been fetched from four external sources, deduplicated, stored in MinIO, parsed into normalized text, scored for quality, tagged with company mentions, and routed to the appropriate extraction queue. The documents sitting on `stonks:queue:extraction` and `stonks:queue:macro_classification` are clean, quality-filtered, and ready for AI processing. [Page 2 — AI Agent Processing and Structured Extraction](02-ai-agent-processing-and-extraction.md) picks up the story from here, explaining how the Document Intelligence Extractor and Global Event Classifier agents use LLM inference to transform these normalized documents into the structured JSON intelligence that feeds the rest of the pipeline.
@@ -0,0 +1,164 @@
# Page 2 — AI Agent Processing and Structured Extraction
Documents that arrive on the `stonks:queue:extraction` and `stonks:queue:macro_classification` Redis queues are clean, quality-filtered, and normalized — but they are still unstructured text. The job of the Extractor service is to transform that text into structured JSON intelligence that the rest of the pipeline can reason about quantitatively. Two AI agents share this responsibility: the Document Intelligence Extractor handles company-specific news, filings, and transcripts, while the Global Event Classifier handles macro-level geopolitical and economic events. Both agents run through the same Ollama-based inference infrastructure, share a common JSON repair pipeline, and persist their results to PostgreSQL and MinIO for downstream consumption and audit.
This page explains how each agent works, what schemas they produce, how the system validates and repairs LLM output, how runtime configuration is resolved from the database, and how the final structured records are persisted. For a visual overview of the full flow from ingestion through extraction, see the [Ingestion to Extraction Flow diagram](diagrams/ingestion-to-extraction-flow.md). For reference-level detail on agent configuration and the variant management API, see the [AI Agents Guide](../ai-agents.md).
---
## The Document Intelligence Extractor
The Document Intelligence Extractor is the primary AI agent in the pipeline. Registered under the slug `document-extractor` in the `ai_agents` database table, it processes every non-macro document that passes through the Parser — news articles, SEC filings, earnings transcripts, and press releases. Its purpose is to read a normalized document and produce a structured JSON object that captures the document's summary, the companies it affects, the sentiment and impact for each company, the catalysts driving that impact, and the evidence supporting the analysis.
The entry point is `services/extractor/main.py`, which runs a continuous worker loop polling the `stonks:queue:extraction` Redis list. When a job arrives, the worker extracts the `document_id`, `ticker`, and `text` fields from the JSON payload. If the job payload does not include the document text directly, the worker fetches it from MinIO using the `normalized_storage_ref` stored in the `documents` table — the Parser uploaded the normalized text to the `stonks-normalized` bucket during the previous pipeline stage (see [Page 1](01-data-ingestion-and-preparation.md)).
The actual LLM inference is handled by `OllamaClient` in `services/extractor/client.py`. The client sends the document to a local Ollama instance via the `/api/chat` HTTP endpoint with `stream=False` and `think=False`. The `think=False` flag is a deliberate performance choice — it disables the model's chain-of-thought reasoning phase, which would otherwise add two to four minutes of latency per document. The client does not use Ollama's `format` parameter for structured output because of a known Ollama bug (#14645) where the format constraint is silently ignored when `think=False` on qwen3.5 models. Instead, the system relies on prompt engineering to produce JSON and repairs any syntax issues after the fact.
The prompt sent to the model has two parts. The system prompt, defined in `services/extractor/prompts.py`, establishes the model's role as a financial document analyst and sets strict output rules: return only a single JSON object, no markdown fences, no explanation text, every schema field is required, use `"other"` for `catalyst_type` when unsure, keep evidence spans under 20 words, and limit key facts to three to five items. The user prompt, built by `build_extraction_prompt()` in the same module, provides the document text along with document-type-specific guidance. Four guidance variants exist — one each for articles, filings, transcripts, and press releases — each calibrated to the conventions and biases of that document type. For example, the filing guidance instructs the model to preserve the precise legal language of SEC documents, while the press release guidance warns that sentiment may be biased positive and directs the model to focus on concrete metrics rather than marketing language.
The user prompt also includes a list of all tracked tickers from the `companies` table, along with rules for how the model should use them. If a tracked ticker appears verbatim in the text, the model must include it in the output with at least one evidence span. If the article discusses a sector or theme that clearly affects a tracked company (oil prices affecting XOM, AI chip demand affecting NVDA), the model should include that company as well. The model is explicitly told not to invent tickers that are not in the provided list. Documents longer than 8,000 characters are truncated before being included in the prompt, with a `[... truncated for extraction ...]` marker appended.
The `OllamaClient` also supports a `context_window` override via the Ollama `num_ctx` option, which can be configured per agent variant through the `AgentConfigResolver` mechanism described later in this page.
---
## The ExtractionResult Schema
The structured output that the Document Intelligence Extractor produces is defined by the `ExtractionResult` Pydantic model in `services/extractor/schemas.py`. Every field is required — the model has no defaults — so the generated JSON schema forces the LLM to produce every field explicitly. The top-level fields are:
**`summary`** — a concise one-to-three sentence summary of the document's main point. This becomes the human-readable description stored in the `document_intelligence` table.
**`companies`** — an array of `CompanyExtractionItem` objects, one per affected company. Each company entry contains:
- `ticker` — the stock ticker symbol (validated against a regex pattern of one to five uppercase letters).
- `company_name` — the full company name as referenced in the document.
- `relevance` — a float between 0.0 and 1.0 indicating how relevant the document is to this company, where 0 means tangential and 1 means the company is the primary subject.
- `sentiment` — one of `positive`, `negative`, `neutral`, or `mixed`, representing the overall sentiment toward this company in the document.
- `impact_score` — a float between 0.0 and 1.0 estimating the magnitude of impact, where 0 is negligible and 1 is highly material.
- `impact_horizon` — one of `intraday`, `1d`, `1d_7d`, `1d_30d`, `30d_90d`, or `90d_plus`, indicating the expected timeframe over which the impact will play out.
- `catalyst_type` — exactly one of `earnings`, `product`, `legal`, `macro`, `supply_chain`, `m_and_a`, `rating_change`, or `other`. The prompt instructs the model to use `other` when none of the specific categories fit.
- `key_facts` — a list of facts explicitly stated in the document. The prompt emphasizes that the model must not infer or fabricate facts.
- `risks` — a list of risks explicitly mentioned in the document.
- `evidence_spans` — short verbatim quotes from the document supporting the analysis. The prompt requests these be kept under 20 words each.
**`macro_themes`** — a list of broad economic or market themes mentioned in the document, such as `rates`, `inflation`, or `ai_capex`.
**`novelty_score`** — a float between 0.0 and 1.0 indicating how novel or surprising the information is. Routine earnings reports score low; unexpected regulatory actions score high. This value feeds into the novelty bonus component of the signal weighting formula described in [Page 3](03-signal-scoring-and-weighted-signals.md).
**`confidence`** — a float between 0.0 and 1.0 representing the model's confidence in the accuracy of its extraction. Lower values indicate ambiguous or incomplete source text. This value becomes the confidence gate input for signal scoring.
**`extraction_warnings`** — a list of issues encountered during extraction, such as `ambiguous_ticker`, `incomplete_text`, or `low_confidence`. These warnings are persisted alongside the intelligence record for operational monitoring.
The JSON schema is generated programmatically from the Pydantic models via `generate_json_schema()` in `services/extractor/schemas.py`, which calls Pydantic's `model_json_schema()` and then inlines all `$defs` references so the schema is self-contained and Ollama-friendly.
---
## The Global Event Classifier
Not all documents describe company-specific developments. Macro news articles — those tagged with `document_type='macro_event'` by the Parser — describe events that affect entire markets, sectors, or economies: trade wars, central bank rate decisions, commodity supply disruptions, geopolitical conflicts. These documents are routed to the `stonks:queue:macro_classification` Redis queue and processed by the Global Event Classifier agent, registered under the slug `event-classifier` in the `ai_agents` table.
The classifier is implemented in `services/extractor/event_classifier.py`. When the extractor worker in `services/extractor/main.py` pops a job and determines that the document type is `macro_event` (either because the job came from the macro queue or because the `documents` table records it as such), it routes the document to `_process_macro_classification()` instead of the standard extraction pipeline. This function calls `classify_global_event()`, which builds a dedicated prompt, sends it to Ollama through the same `OllamaClient` infrastructure, parses the response, and persists the result.
The classifier's system prompt is distinct from the extractor's. It establishes the model's role as a macro-level news classifier and includes explicit anti-hallucination rules that are critical to preventing the classifier from overreaching. The prompt states that the model should only classify articles about macro events that affect entire markets, sectors, or economies — trade wars, interest rate changes, commodity supply disruptions, regulatory changes, geopolitical conflicts, natural disasters. It explicitly lists what should not be classified as macro events: individual company earnings, lawsuits against a single company, single-company management changes, individual stock analysis, company-specific debt or bankruptcy, and product launches by one company. For these company-specific articles that were incorrectly routed, the model is instructed to set severity to `"low"`, confidence below 0.3, and leave the `affected_regions`, `affected_sectors`, and `affected_commodities` arrays empty.
The user prompt, built by `build_event_classification_prompt()`, reinforces these anti-hallucination rules and provides additional guidance. It instructs the model to only extract facts explicitly stated in the text, to set confidence below 0.4 for vague or speculative content, to distinguish announced policy from rumored policy, and to reserve `"critical"` severity for events affecting multiple countries or entire global markets. Articles longer than 6,000 characters are truncated before inclusion in the prompt.
The output schema is the `GlobalEvent` dataclass, which contains:
- `event_types` — a list of impact type strings, drawn from a fixed set: `supply_disruption`, `demand_shift`, `cost_increase`, `regulatory_pressure`, `currency_impact`, `commodity_shock`, `trade_barrier`, and `geopolitical_risk`. The model is instructed to include all applicable types rather than collapsing to a single category.
- `severity` — one of `low`, `moderate`, `high`, or `critical`.
- `affected_regions` — ISO 3166-1 alpha-2 country codes or region names (e.g., `US`, `CN`, `EU`, `GB`, `JP`). Only regions explicitly mentioned or clearly implied should be included.
- `affected_sectors` — GICS sector identifiers such as `Energy`, `Financials`, `Information Technology`, or `Industrials`.
- `affected_commodities` — commodity identifiers like `crude_oil`, `natural_gas`, `gold`, `copper`, `wheat`, `lithium`, or `semiconductors`. An empty list if no commodities are directly affected.
- `summary` — a one-to-three sentence summary of the event and its market implications.
- `key_facts` — facts explicitly stated in the article, limited to three to five items.
- `estimated_duration` — one of `short_term` (days to weeks), `medium_term` (weeks to months), or `long_term` (months to years).
- `confidence` — a float between 0.0 and 1.0, clamped during parsing.
Each `GlobalEvent` also carries a `model_metadata` object recording the provider (`ollama`), model name, prompt version (`event-classification-v1`), and schema version (`1.0.0`), plus a `source_document_id` linking back to the originating document.
After a successful classification, the system computes macro impact records for all tracked companies using the exposure-based interpolation engine in `services/aggregation/interpolation.py`. Each company's exposure profile — geographic revenue mix, supply chain regions, key input commodities, regulatory jurisdictions, and market position tier — determines how much a given macro event affects that company. Companies with non-zero macro impact scores get `macro_impact_records` rows persisted to PostgreSQL, and aggregation jobs are enqueued to `stonks:queue:aggregation` for each affected ticker. The extractor worker tracks consecutive macro classification failures and emits a critical-level alert after three consecutive failures, continuing with company-only signals in the meantime.
---
## The JSON Repair Pipeline
LLM output is inherently unreliable at the syntactic level. Models sometimes wrap JSON in markdown fences, produce trailing commas, leave strings unterminated, or truncate output mid-object when they hit token limits. The extractor addresses this with a three-stage JSON repair pipeline implemented across `services/extractor/client.py` and `services/extractor/schemas.py`.
The first stage is a direct `json.loads()` call. If the raw model output is already valid JSON, no repair is needed and the pipeline moves straight to validation. This is the fast path for well-behaved model responses.
The second stage strips markdown fences. Models frequently wrap their output in `` ```json ... ``` `` blocks despite being told not to. The `_strip_markdown_fences()` function in `services/extractor/client.py` uses a regex to detect and remove these wrappers before attempting another parse.
The third stage invokes the `json-repair` library as a fallback. The `_repair_json()` function in `services/extractor/client.py` calls `repair_json()` with `return_objects=False` to get a repaired JSON string. This library handles a wide range of common LLM JSON errors — trailing commas, missing quotes, unescaped characters — that would otherwise require custom repair logic.
The `services/extractor/schemas.py` module contains an additional layer of repair logic in its own `_repair_json()` function, which handles cases that the library might miss. It strips non-JSON prefixes (models sometimes prepend explanatory text before the opening brace), removes control characters that break parsing, fixes trailing commas before closing brackets, and as a last resort calls `_repair_truncated_json()` — a state-machine parser that walks the string tracking bracket depth and string state, then appends the necessary closing tokens to complete a truncated JSON object.
For the Global Event Classifier, the `_parse_classification_response()` function in `services/extractor/event_classifier.py` reuses the same `_strip_markdown_fences()` and `_repair_json()` functions from the client module, and additionally handles the case where the model wraps the output object in a single-element list — a quirk observed with some model configurations.
---
## Structural and Semantic Validation
Repairing JSON syntax is only the first step. The `validate_extraction()` function in `services/extractor/schemas.py` performs both structural and semantic validation on the parsed output, and the distinction between the two is important for understanding the retry logic.
Structural validation begins with normalization. The `_normalize_extraction_data()` function fills in missing top-level fields with sensible defaults (empty summary, empty companies array, 0.5 novelty score, 0.3 confidence), clamps numeric fields to the [0.0, 1.0] range, and normalizes per-company fields. Catalyst types that the model produces as free-text alternatives — `"strategic pivot"`, `"acquisition"`, `"lawsuit"`, `"inflation"`, `"launch"` — are mapped to their canonical enum values through a comprehensive alias dictionary. Impact horizons like `"long-term"`, `"short"`, `"immediate"`, or `"near-term"` are similarly mapped to the valid set (`intraday`, `1d`, `1d_7d`, `1d_30d`, `30d_90d`, `90d_plus`). After normalization, the data is validated against the `ExtractionResult` Pydantic model, which enforces type constraints, enum membership, and range bounds.
Semantic validation catches issues that are structurally valid but logically suspect. The `_semantic_checks()` function runs a series of cross-field consistency checks that produce either errors (which trigger a retry) or warnings (which are logged but do not block acceptance). Semantic errors include duplicate tickers across company entries, missing ticker fields, and invalid impact horizon values. Semantic warnings include empty summaries, low confidence with companies present, invalid ticker formats (not matching the one-to-five uppercase letter pattern), missing evidence spans, evidence spans that are too short (under 8 characters) or too long (over 500 characters), high impact scores with no supporting key facts, very low relevance scores, and strong sentiment paired with negligible impact scores.
When the original document text is available, the validator also performs an evidence grounding check: each evidence span is searched for in the source text (case-insensitive), and spans not found in the document are flagged with a warning. This helps detect hallucinated evidence — quotes the model fabricated rather than extracted from the actual text.
If validation produces any semantic errors, the `ValidationReport` is marked as invalid and the `OllamaClient` retry loop treats it as a failed attempt. The retry logic uses exponential backoff with configurable parameters: a base delay (default from `OllamaConfig`), a multiplier applied on each retry, and a maximum delay cap. The number of retries is configurable per agent through the `max_retries` field in the `ai_agents` or `agent_variants` table. Non-retryable errors — HTTP 400, 401, 403, 404, and 422 responses from Ollama — short-circuit the retry loop immediately, since these indicate a problem with the request itself rather than a transient model failure.
Every attempt, whether successful or not, is recorded in an `ExtractionAttempt` dataclass that captures the raw output, validation report, error description, duration in milliseconds, model name, and whether the error was retryable. The full list of attempts is preserved in the `ExtractionResponse` for audit purposes and uploaded to MinIO by the persistence layer.
---
## The AgentConfigResolver: Hot-Swapping Models and Prompts
Both the Document Intelligence Extractor and the Global Event Classifier resolve their runtime configuration through the `AgentConfigResolver` in `services/shared/agent_config.py`. This mechanism allows operators to change models, prompts, timeouts, retry counts, and token budgets without restarting any service — changes take effect within 60 seconds.
The resolver works by querying the `ai_agents` and `agent_variants` PostgreSQL tables with a single SQL statement that uses `COALESCE` to prefer variant values over base agent values. When the extractor worker starts, it creates an `AgentConfigResolver` instance with a 60-second TTL cache and calls `resolver.resolve("document-extractor")` to get the active configuration. If an active variant exists for the agent (enforced by a unique partial index on `agent_variants` that allows at most one active variant per agent), the variant's `model_name`, `system_prompt`, `temperature`, `max_tokens`, `context_window`, `timeout_seconds`, and `max_retries` override the base agent's values wherever the variant provides a non-NULL value. If no active variant exists, the base agent's configuration is used. If the database query fails entirely, the resolver returns `None` and the worker falls back to environment-variable-based `OllamaConfig` defaults.
The resolved configuration is captured in a `ResolvedAgentConfig` frozen dataclass that includes the `agent_id`, `variant_id` (if any), `model_provider`, `model_name`, `system_prompt`, `user_prompt_template`, `prompt_version`, `temperature`, `max_tokens`, `context_window`, `input_token_limit`, `token_budget`, `timeout_seconds`, and `max_retries`. The extractor worker uses this to build an `OllamaConfig` that is passed to the `OllamaClient`.
The 60-second TTL cache means the resolver only hits the database once per minute per agent slug. Cache entries are keyed by slug and timestamped with `time.monotonic()`. When a cached entry expires, the next `resolve()` call re-queries the database and refreshes the cache. The `invalidate()` method can clear a single slug or the entire cache, though in practice the TTL-based expiry is sufficient for normal operations.
The extractor worker re-resolves its configuration every 100 jobs. If the resolved model name has changed (for example, because an operator activated a variant that uses a different model), the worker closes the old `OllamaClient` and creates a new one with the updated configuration. The event classifier is resolved separately and can use a different model than the document extractor — the worker maintains two independent `OllamaClient` instances when the models differ.
Token budget enforcement adds another layer of control. If a variant specifies a `token_budget` (total tokens per hour), the worker checks the `agent_performance_log` table before each invocation to see whether the budget has been exceeded. If so, the invocation is skipped entirely. Input token limits work similarly: if a variant sets an `input_token_limit`, the worker truncates the document text to approximately that many tokens (estimated at four characters per token) before sending it to the model.
For a complete guide to creating variants, activating them, and comparing their performance, see the [AI Agents Guide](../ai-agents.md).
---
## Persistence: From Extraction to Database
Once the LLM produces a valid extraction and it passes validation, the `persist_extraction()` function in `services/extractor/worker.py` orchestrates the full persistence pipeline. This function writes to both MinIO (for audit) and PostgreSQL (for downstream consumption), ensuring that every extraction attempt is fully traceable.
The MinIO persistence layer uploads four artifacts per extraction, all stored under date-partitioned paths in dedicated buckets. The prompt metadata (prompt version, schema version, model name) goes to `stonks-llm-prompts`. The raw model output for every attempt — including failed ones — goes to `stonks-llm-results`, preserving the full retry history. A validation report summarizing the final attempt's status, errors, and warnings is uploaded alongside the raw output. On success, the final parsed intelligence object (the `ExtractionResult` serialized as JSON) is uploaded to a separate path for easy retrieval.
The PostgreSQL persistence writes to two tables. The `document_intelligence` table receives one row per document, containing the summary, macro themes, novelty score, source credibility, extraction warnings, confidence, model metadata (provider, model name, prompt version, schema version), references to the MinIO artifacts (raw output ref, prompt ref), validation status (`valid` or `failed`), validation errors, and retry count. This row is the authoritative record of what the AI extracted from the document.
The `document_impact_records` table receives one row per company mention within the extraction. Each impact record is linked to the parent `document_intelligence` row via `intelligence_id` and to the `companies` table via `company_id`. The record captures the ticker, relevance, sentiment, impact score, impact horizon, catalyst type, key facts, risks, and evidence spans for that specific company. The `company_id` is resolved from a ticker-to-UUID mapping that the worker maintains by querying the `companies` table (refreshed every 100 jobs). If a ticker in the extraction output does not match any tracked company, the impact record is skipped with a warning — the system only persists impact records for companies in its tracked universe.
After persisting the intelligence and impact records, the worker updates the document's status in the `documents` table to `extracted` (or `extraction_failed` if all retry attempts were exhausted). Even failed extractions get a `document_intelligence` row with `validation_status='failed'`, empty summary, zero confidence, and the accumulated error messages — this ensures the failure is visible in the database rather than silently lost.
Performance metrics are collected for every extraction via `collect_metrics()` in `services/extractor/metrics.py` and persisted to a metrics table. Prometheus counters and histograms track extraction attempts, duration, retries, confidence distribution, validation errors, and estimated token usage (input and output, estimated at four characters per token). When a resolved agent config is available, the worker also logs to the `agent_performance_log` table with variant attribution, enabling the A/B comparison queries described in the [AI Agents Guide](../ai-agents.md).
For the Global Event Classifier, persistence follows a parallel path. The prompt and raw output are uploaded to MinIO under an `event_classification/macro/` path prefix. The parsed `GlobalEvent` is persisted to the `global_events` PostgreSQL table, which stores the event types, severity, affected regions, affected sectors, affected commodities, summary, key facts, estimated duration, confidence, source document ID, and model metadata. Downstream, the macro interpolation engine computes `macro_impact_records` for each affected company and persists those as well.
---
## Enqueuing Aggregation Jobs
The final step in the extraction pipeline is to notify the downstream aggregation engine that new intelligence is available. After a successful document extraction, the worker pushes a job onto the `stonks:queue:aggregation` Redis list containing the ticker of the affected company. The aggregation engine (described in [Page 3](03-signal-scoring-and-weighted-signals.md)) will pick up this job and recompute the weighted signals and trend summaries for that ticker, incorporating the freshly extracted intelligence.
For macro events, the enqueue logic is more expansive. After the Global Event Classifier produces a `GlobalEvent` and the interpolation engine computes macro impact records, the worker enqueues an aggregation job for every ticker that received a non-zero macro impact score. A single macro event — say, a new tariff announcement affecting the Energy and Industrials sectors — can trigger aggregation recomputation for dozens of tickers simultaneously. The aggregation job payload includes both the `ticker` and the `macro_event_id`, so the aggregation engine knows to incorporate the new macro signals.
The worker alternates between the extraction and macro classification queues to prevent starvation: every third job is pulled from `stonks:queue:macro_classification`, with the remaining two-thirds from `stonks:queue:extraction`. If the preferred queue is empty, the worker falls back to the other queue, ensuring that neither pipeline stalls while the other has work available.
---
## What Comes Next
At this point, documents have been transformed from unstructured text into structured JSON intelligence — `ExtractionResult` objects for company-specific documents and `GlobalEvent` objects for macro news. These structured records are persisted in PostgreSQL and their tickers have been enqueued for aggregation. But raw extraction output is not yet actionable for trading decisions. The extraction tells us that a document is bearish for AAPL with an impact score of 0.7 and a confidence of 0.8, but it does not tell us how much weight that signal should carry relative to other signals about AAPL, or how it compares to signals from different sources, time periods, or market conditions. [Page 3 — Signal Scoring and the WeightedSignal Abstraction](03-signal-scoring-and-weighted-signals.md) picks up the story from here, explaining how the aggregation engine transforms these raw extraction outputs into weighted signals through confidence gating, recency decay, source credibility scoring, novelty bonuses, and market context multipliers.
@@ -0,0 +1,210 @@
# Page 3 — Signal Scoring and the WeightedSignal Abstraction
The extraction pipeline described in [Page 2](02-ai-agent-processing-and-extraction.md) produces structured intelligence records — `document_impact_records` for company-specific documents, `macro_impact_records` for global events, and `competitive_signal_records` for cross-company pattern propagation. Each record carries a sentiment, an impact score, a confidence value, and a publication timestamp. But these raw values are not directly comparable. A high-confidence extraction from a reputable source published ten minutes ago should carry far more weight than a low-confidence extraction from an unknown source published three weeks ago. A document that breaks genuinely novel information should matter more than one that rehashes yesterday's earnings call. And when the market is moving fast — high volatility, surging volume — fresh signals become even more critical.
The signal scoring layer in `services/aggregation/scoring.py` solves this problem by transforming each raw intelligence record into a `WeightedSignal` object: a document reference paired with a composite aggregation weight that encodes recency, credibility, novelty, confidence, and market conditions into a single number. This page explains how that weight is computed, how sentiment labels become numeric values, and how three independent signal layers — Company, Macro, and Competitive — each produce `WeightedSignal` objects that are concatenated into a unified list before the aggregation engine computes trend summaries. For a visual breakdown of the composite weight formula, see the [Weighted Signal Computation diagram](diagrams/weighted-signal-computation.md). For the full picture of how the three layers merge, see the [Three-Layer Signal Merging diagram](diagrams/three-layer-signal-merging.md).
---
## The WeightedSignal and SignalWeight Dataclasses
The core abstraction is the `WeightedSignal` dataclass, defined in `services/aggregation/scoring.py`. It pairs a document reference with the computed weight and the signal's sentiment and impact values:
- **`document_id`** — the UUID of the source document (for company and macro signals) or a synthetic identifier for pattern-derived signals (e.g., `pattern:AAPL:earnings:7d`).
- **`weight`** — a `SignalWeight` object containing the component breakdown and the final combined score.
- **`sentiment_value`** — a numeric sentiment value: `+1.0` for positive, `-1.0` for negative, `0.0` for neutral or mixed.
- **`impact_score`** — the magnitude of impact, drawn from the extraction's per-company impact score for company signals, or scaled by a layer-specific weight multiplier for macro and competitive signals.
The `SignalWeight` dataclass captures the individual components that feed into the combined weight, making the scoring decision fully transparent and auditable:
- **`recency`** — the exponential decay weight based on document age.
- **`credibility`** — the source credibility weight after clamping and exponentiation.
- **`novelty_bonus`** — the additive bonus derived from the document's novelty score.
- **`confidence_gate`** — either `1.0` (signal passes) or `0.0` (signal is gated out).
- **`market_ctx_multiplier`** — a multiplicative boost from market conditions, always `>= 1.0`.
- **`combined`** — the final composite weight used by the aggregation engine.
The `ScoringConfig` frozen dataclass holds all tunable parameters for the scoring functions — half-life hours per window, credibility bounds, novelty bonus cap, confidence floor, and market context thresholds. A module-level `DEFAULT_CONFIG` singleton provides the production defaults, but every scoring function accepts an optional `config` parameter so that tests and alternative configurations can override any parameter without modifying global state.
---
## The Composite Weight Formula
The `compute_signal_weight()` function in `services/aggregation/scoring.py` computes the combined weight for a single document signal. The formula is:
```
combined = gate × recency × credibility × (1 + novelty_bonus) × market_context_multiplier
```
Each factor is computed independently and then multiplied together. This multiplicative structure means that any single factor can zero out the entire weight (the confidence gate) or amplify it (the market context multiplier), and the interaction between factors is naturally captured — a highly credible, very recent document with novel information in a volatile market receives the maximum possible weight, while a stale, low-credibility document with routine information receives a weight close to zero.
The following sections describe each component in detail.
---
## Confidence Gate
The confidence gate is the first and most decisive filter. If the extraction confidence for a document falls below the `confidence_floor` threshold — set to `0.2` in the default `ScoringConfig` — the gate evaluates to `0.0` and the entire combined weight becomes zero. The document is effectively excluded from aggregation. If the confidence meets or exceeds the threshold, the gate evaluates to `1.0` and has no further effect on the weight.
This binary gate exists because documents with very low extraction confidence are too unreliable to aggregate. A confidence of 0.15 typically means the LLM struggled to parse the document — perhaps the text was truncated, the language was ambiguous, or the document type was unusual. Including such signals would add noise rather than information. The threshold of 0.2 is deliberately low; it filters only the most unreliable extractions while allowing moderately confident signals to participate (their lower confidence is reflected through the credibility component instead).
---
## Recency Decay
The `recency_weight()` function computes an exponential decay based on how old a document is relative to the aggregation anchor time. The formula is:
```
w = 2^(age_hours / half_life)
```
A document published exactly one half-life ago receives a recency weight of `0.5`. A document published two half-lives ago receives `0.25`, and so on. A document published at or after the reference time receives the maximum weight of `1.0`.
The half-life varies by trend window, reflecting the intuition that shorter windows need faster decay to stay responsive, while longer windows should give older documents more influence. The default half-lives, configured in `ScoringConfig.half_life_hours`, are:
| Window | Half-Life |
|--------|-----------|
| `intraday` | 2 hours |
| `1d` | 12 hours |
| `7d` | 72 hours (3 days) |
| `30d` | 240 hours (10 days) |
| `90d` | 720 hours (30 days) |
For the intraday window, a document published four hours ago already has a recency weight of `0.25` — it is rapidly losing influence as newer information arrives. For the 90-day window, that same four-hour-old document still has a recency weight of essentially `1.0`, because the 30-day half-life means age only becomes significant over weeks.
A floor value of `min_recency_weight = 0.01` prevents very old documents from being completely zeroed out. Even a document from months ago retains a trace-level weight of 1%, ensuring it can still contribute to trend computation if no newer signals exist. Both timestamps are normalized to UTC; naive datetimes are treated as UTC to avoid timezone-related scoring errors.
---
## Source Credibility
The `credibility_weight()` function transforms a source's credibility score into a weight component. The raw credibility value — a float between 0.0 and 1.0 stored in the `document_intelligence` table — is first clamped to the range `[0.1, 1.0]` using the `credibility_floor` and `credibility_ceiling` parameters from `ScoringConfig`. This clamping ensures that even the least credible sources retain a minimum weight of 0.1 rather than being completely silenced, while preventing any source from exceeding a weight of 1.0.
After clamping, the value is raised to the `credibility_exponent` power. The default exponent is `1.0`, which means the clamped credibility passes through unchanged. Setting the exponent above 1.0 would penalize low-credibility sources more aggressively — for example, an exponent of 2.0 would reduce a credibility of 0.5 to a weight of 0.25. Setting it below 1.0 would flatten the curve, making the system more tolerant of lower-credibility sources. The exponent is configurable through `ScoringConfig` to allow operators to tune the credibility sensitivity without changing the scoring code.
---
## Novelty Bonus
The novelty bonus rewards documents that contain genuinely new information. The bonus is computed as:
```
novelty_bonus = novelty_score × novelty_bonus_max
```
where `novelty_score` is the 0.0-to-1.0 value produced by the extraction model (see the `ExtractionResult` schema in [Page 2](02-ai-agent-processing-and-extraction.md)) and `novelty_bonus_max` is `0.25` by default. This means the bonus ranges from `0.0` (completely routine information) to `0.25` (maximally novel information), providing up to a 25% boost to the signal weight.
The bonus enters the composite formula as `(1 + novelty_bonus)`, so it acts as a multiplicative amplifier on the base weight. A document with a novelty score of 1.0 gets its weight multiplied by 1.25; a document with a novelty score of 0.0 gets multiplied by 1.0 (no change). This design ensures that novelty can only increase a signal's weight, never decrease it — routine information is not penalized, it simply does not receive the bonus.
---
## Market Context Multiplier
The `market_context_multiplier()` function computes a boost factor based on real-time market conditions for the ticker being aggregated. The multiplier is always `>= 1.0`, meaning market context can only amplify signal weights, never reduce them. When no market context data is available (the `MarketContext` object from `services/shared/schemas.py` has `has_data == False`), the multiplier defaults to `1.0`.
Two market features contribute to the boost:
**Volatility boost.** When the ticker's price volatility exceeds the `volatility_recency_boost_threshold` (default `1.0` in price units), the excess volatility is transformed through a logarithmic scaling function: `log₁₊(excess) × 0.15`. The logarithmic scaling prevents extreme volatility from producing runaway weight amplification. The boost is capped at `volatility_recency_boost_max = 0.30`, so the maximum volatility contribution is a 30% weight increase. The rationale is that in highly volatile markets, fresh intelligence is disproportionately valuable — a signal about NVDA matters more when NVDA is swinging 5% intraday than when it is trading in a tight range.
**Volume surge boost.** When the ticker's volume change percentage exceeds `volume_surge_threshold_pct = 50.0%` (meaning trading volume is at least 50% above the prior period's average), a flat `volume_surge_boost = 0.15` is added. Unlike the volatility boost, this is binary — either the volume threshold is met and the full 15% boost applies, or it is not and no boost is added. High-volume moves carry more conviction because they represent broader market participation rather than thin-market noise.
The two boosts are additive within the multiplier: `multiplier = 1.0 + volatility_boost + volume_surge_boost`. In the most extreme case — high volatility and a volume surge — the combined multiplier reaches `1.0 + 0.30 + 0.15 = 1.45`, amplifying the signal weight by 45%. The `MarketContext` data is fetched by `services/aggregation/market_context.py` from the market data tables in PostgreSQL, using the same ticker and window parameters as the impact record query.
---
## Sentiment Mapping
Before signals can be aggregated into trend summaries, the categorical sentiment labels from the extraction output must be converted to numeric values. The `sentiment_to_numeric()` function in `services/aggregation/scoring.py` performs this mapping:
| Sentiment Label | Numeric Value |
|----------------|---------------|
| `positive` | `+1.0` |
| `negative` | `-1.0` |
| `neutral` | `0.0` |
| `mixed` | `0.0` |
The mapping is case-insensitive. Any unrecognized label defaults to `0.0`. The choice to map both `neutral` and `mixed` to `0.0` is deliberate — a mixed-sentiment document (one that contains both positive and negative signals for the same company) should not push the trend in either direction. The contradiction between the positive and negative aspects is captured separately by the contradiction detection system described in [Page 4](04-trend-aggregation-and-accumulating-signals.md), rather than being baked into the sentiment value itself.
For macro signals, the direction-to-sentiment mapping in `services/aggregation/worker.py` follows the same pattern: `positive` maps to `+1.0`, `negative` to `-1.0`, and both `mixed` and `neutral` to `0.0`. For competitive signals built by `build_pattern_weighted_signals()` in `services/aggregation/signal_propagation.py`, the sentiment is derived from the pattern's directional bias: `+1.0` if `bullish_pct > bearish_pct`, `-1.0` otherwise.
---
## Weighted Sentiment Average
The `weighted_sentiment_average()` function computes the central metric that drives trend direction: a weight-adjusted average sentiment across all signals for a ticker in a given window. The formula is:
```
weighted_avg = Σ(combined_weight × impact_score × sentiment_value) / Σ(combined_weight × impact_score)
```
Each signal contributes its sentiment value scaled by both its composite weight and its impact score. The denominator normalizes by the total effective weight, producing a value in the range `[-1.0, +1.0]`. A result near `+1.0` means the weighted evidence is overwhelmingly positive; near `-1.0` means overwhelmingly negative; near `0.0` means either neutral or evenly split.
The use of `combined_weight × impact_score` as the effective weight means that high-impact, high-weight signals dominate the average. A single high-confidence, recent, credible document with a strong impact score can outweigh several older, lower-impact documents — which is the intended behavior. The aggregation engine in `services/aggregation/worker.py` passes this weighted average to `derive_trend_direction()`, which maps it to a `TrendDirection` enum value (bullish, bearish, mixed, or neutral) using the thresholds described in [Page 4](04-trend-aggregation-and-accumulating-signals.md).
If the total effective weight is zero — either because no signals exist or all signals were gated out by the confidence floor — the function returns `0.0`, which maps to a neutral trend direction.
---
## The Three Signal Layers
The aggregation engine in `services/aggregation/worker.py` does not treat all intelligence sources equally. Signals flow through three independent layers, each with a different relative weight, before being concatenated into a single `WeightedSignal` list for trend computation. This layered architecture allows the system to incorporate diverse intelligence sources while controlling how much influence each source type has on the final trend.
### Layer 1 — Company Signals (Weight: 1.0)
Company signals are the primary layer. They are built by `build_weighted_signals()` in `services/aggregation/worker.py` from `document_impact_records` — the per-company extraction output produced by the Document Intelligence Extractor (see [Page 2](02-ai-agent-processing-and-extraction.md)). Each impact record's sentiment is converted via `sentiment_to_numeric()`, and its impact score is used directly without any layer-level scaling. The `compute_signal_weight()` function produces the composite weight using the document's publication time, source credibility, novelty score, extraction confidence, and the ticker's current market context.
Company signals carry a relative weight of `1.0` — they are the baseline against which other layers are measured. This reflects the design principle that direct, company-specific intelligence (an earnings report about AAPL, a product launch by TSLA, a lawsuit against META) is the most relevant and reliable signal for that company's trend.
### Layer 2 — Macro Signals (Weight: 0.3)
Macro signals capture the indirect impact of global events on individual companies. They are built by `build_macro_weighted_signals()` in `services/aggregation/worker.py` from `macro_impact_records` — the per-company impact scores computed by the exposure-based interpolation engine after the Global Event Classifier processes a macro news article. The sentiment is mapped from the `impact_direction` field (`positive``+1.0`, `negative``-1.0`, `mixed`/`neutral``0.0`), and the impact score is scaled by `MACRO_SIGNAL_WEIGHT`, which defaults to `0.3` in `AggregationConfig`.
The 0.3 weight means that a macro signal's impact score is reduced to 30% of its raw value before entering the aggregation. This attenuation reflects the inherent uncertainty in macro-to-company impact estimation — a tariff announcement might affect XOM's revenue, but the magnitude depends on exposure profiles, supply chain flexibility, and competitive dynamics that the interpolation engine can only approximate. By weighting macro signals at 0.3 relative to company signals at 1.0, the system ensures that macro intelligence informs the trend without overwhelming direct company-specific evidence.
The recency decay, credibility, and confidence gating for macro signals use the same `compute_signal_weight()` function as company signals. The `published_at` timestamp comes from the global event's source document (the macro news article), and the `source_credibility` and `extraction_confidence` both use the macro impact record's `confidence` field.
### Layer 3 — Competitive Signals (Weight: 0.2)
Competitive signals capture cross-company effects: when a catalyst hits one company, historical patterns suggest how competitors might be affected. They are built by `build_pattern_weighted_signals()` in `services/aggregation/signal_propagation.py` from two sources: `HistoricalPattern` objects (self-company patterns mined by `services/aggregation/pattern_matcher.py`) and `CompetitiveSignalRecord` objects (cross-company propagation signals stored in `competitive_signal_records`).
For historical patterns, the sentiment is derived from the pattern's directional bias (`+1.0` if `bullish_pct > bearish_pct`, `-1.0` otherwise), and the impact score is the pattern's `avg_strength` multiplied by `competitive_signal_weight` (default `0.2` from `CompetitiveConfig`). The `published_at` for recency decay uses the pattern's `data_end` — the most recent data point in the pattern's sample — and the `extraction_confidence` uses the pattern's `pattern_confidence`. Source credibility is set to `1.0` because patterns are derived from validated historical data, and novelty is fixed at `0.5`.
For competitive signal records, the same structure applies: sentiment from `signal_direction`, impact from `signal_strength × competitive_signal_weight`, recency from `computed_at`, and confidence from `pattern_confidence`.
The 0.2 weight makes competitive signals the lightest layer. This is appropriate because competitive signal propagation involves the most inference — the system is predicting how Company B will react based on what happened to Company A in historically similar situations. The signal is valuable as supplementary evidence but should not drive trend direction on its own.
---
## Signal Merging in the Aggregation Engine
The `aggregate_company_window()` function in `services/aggregation/worker.py` orchestrates the merging of all three layers for a single ticker and window. The process follows a clear sequence:
1. **Fetch company impact records** from `document_impact_records` for the ticker within the window's time range.
2. **Fetch market context** for the ticker from market data tables.
3. **Build company weighted signals** via `build_weighted_signals()`.
4. **Check the macro toggle** — query `risk_configs` for the `macro_enabled` flag, then fetch and merge macro signals if enabled.
5. **Check the competitive toggle** — query `risk_configs` for the `competitive_enabled` flag, then fetch patterns, fetch competitive signals, and merge if enabled.
6. **Concatenate** all `WeightedSignal` lists into a single list.
7. **Assemble the `TrendSummary`** from the merged signals.
The concatenation in step 6 is a simple list append — `signals = signals + macro_signals` followed by `signals = signals + pattern_weighted`. There is no re-weighting or normalization at the merge point. The relative influence of each layer is already encoded in the impact scores (scaled by 0.3 for macro, 0.2 for competitive, 1.0 for company) and in the composite weights computed by `compute_signal_weight()`. The `weighted_sentiment_average()` function then naturally produces a sentiment average that reflects these relative weights.
---
## Runtime Toggles and Graceful Degradation
Both the macro and competitive signal layers can be enabled or disabled at runtime through the `risk_configs` PostgreSQL table, without restarting any service. The toggle state is read fresh from the database at the start of every aggregation cycle — there is no caching — so changes take effect on the very next cycle.
The `fetch_macro_enabled()` function in `services/aggregation/worker.py` queries the most recent active `risk_configs` row and reads the `config->>'macro_enabled'` JSON field. If the field is explicitly set to `"true"` or `"false"`, that value overrides the `AggregationConfig` default. If no config row exists or the field is absent, the function returns `None` and the engine falls back to the `AggregationConfig.macro_enabled` default (which is `True`). The `fetch_competitive_enabled()` function follows the identical pattern for the `competitive_enabled` field.
When a layer is disabled, the aggregation engine simply skips the fetch-and-merge step for that layer. Company signals are always computed — they cannot be toggled off. This means the system degrades gracefully: disabling the macro layer produces trends based on company signals alone (plus competitive signals if enabled), and disabling the competitive layer produces trends based on company and macro signals. Disabling both layers reduces the engine to its original single-layer behavior, using only direct document intelligence.
Crucially, disabling a layer does not stop upstream processing. When the macro layer is disabled, the Global Event Classifier continues to classify macro events and the interpolation engine continues to compute `macro_impact_records`. The data accumulates in PostgreSQL. When the layer is re-enabled, the aggregation engine immediately picks up all the macro impact records that were computed while the layer was disabled — there is no data loss or gap in coverage. The same applies to competitive signals: pattern mining and signal propagation continue regardless of the toggle state.
If the competitive signal fetch fails at runtime (for example, due to a database timeout), the aggregation engine catches the exception, logs it, and continues with company and macro signals only. This exception-based graceful degradation ensures that a transient failure in one layer does not block trend computation entirely.
---
## What Comes Next
At this point, every document intelligence record, macro impact record, and competitive signal record has been transformed into a `WeightedSignal` with a composite weight that encodes recency, credibility, novelty, confidence, and market conditions. The three signal layers have been merged into a single list, and the weighted sentiment average has been computed. But a single aggregation cycle produces only a snapshot — a point-in-time view of the evidence. The real power of the system emerges when these snapshots accumulate across multiple documents and time windows, building a case for action. [Page 4 — Trend Aggregation and Accumulating Signals](04-trend-aggregation-and-accumulating-signals.md) explains how the aggregation engine computes `TrendSummary` objects across five time windows, how consecutive same-direction signals strengthen trend confidence and escalate the system's response from neutral observation to actionable trading recommendations, and how contradiction detection and evidence ranking ensure that the trend reflects genuine consensus rather than noise.
@@ -0,0 +1,267 @@
# Page 4 — Trend Aggregation and Accumulating Signals
The scoring layer described in [Page 3](03-signal-scoring-and-weighted-signals.md) transforms every intelligence record into a `WeightedSignal` — a document reference paired with a composite weight that encodes recency, credibility, novelty, confidence, and market conditions. Three independent signal layers (Company at weight 1.0, Macro at 0.3, Competitive at 0.2) each produce `WeightedSignal` objects that are concatenated into a single list. But a single list of weighted signals is still just raw material. The aggregation engine in `services/aggregation/worker.py` is where that raw material becomes a decision-grade assessment: a `TrendSummary` object that captures the direction, strength, confidence, contradiction level, and supporting evidence for a ticker across a specific time window. This page explains how that transformation works — from weighted sentiment averages through trend direction derivation, contradiction detection, evidence ranking, and confidence computation — and, critically, how consecutive signals pointing in the same direction accumulate across documents and time windows to escalate the system's response from passive observation to actionable trading recommendations.
For a visual overview of the accumulation and escalation process, see the [Trend Accumulation and Escalation diagram](diagrams/trend-accumulation-escalation.md). For how the three signal layers merge into the aggregation engine, see the [Three-Layer Signal Merging diagram](diagrams/three-layer-signal-merging.md).
---
## Five Time Windows
The aggregation engine does not compute a single trend for each ticker. It computes five, one for each time window defined in `services/aggregation/worker.py`:
| Window | Lookback Duration |
|--------|-------------------|
| `intraday` | 12 hours |
| `1d` | 1 day |
| `7d` | 7 days |
| `30d` | 30 days |
| `90d` | 90 days |
Each window produces an independent `TrendSummary` by fetching all impact records, macro impacts, and competitive signals for the ticker within that window's time range. The `aggregate_company_window()` function in `services/aggregation/worker.py` orchestrates this per-window computation: it determines the time range from the window's lookback duration, fetches `document_impact_records` from PostgreSQL, retrieves market context, builds company weighted signals, checks the macro and competitive runtime toggles (see [Page 3](03-signal-scoring-and-weighted-signals.md) for toggle details), merges any enabled layer signals, and then assembles the `TrendSummary`.
The five-window design serves a specific purpose. Short windows (intraday, 1d) capture fast-moving sentiment shifts — a breaking earnings miss, a sudden regulatory action — while long windows (30d, 90d) reveal sustained trends that persist across many documents and news cycles. A ticker might show a bearish intraday trend after a single negative article, but a neutral 30-day trend because the broader evidence base is balanced. The recommendation engine downstream (described in [Page 5](05-recommendation-generation.md)) evaluates each window's `TrendSummary` independently, so the system can respond to both short-term catalysts and long-term directional shifts.
The `aggregate_company()` function iterates over all effective windows (configurable via `AggregationConfig.windows`, defaulting to all five) and calls `aggregate_company_window()` for each one. This means a single aggregation cycle for one ticker produces up to five `TrendSummary` objects, each reflecting a different temporal perspective on the same underlying evidence.
---
## Trend Direction Derivation
Once the weighted sentiment average has been computed from the merged signal list (see the `weighted_sentiment_average()` function described in [Page 3](03-signal-scoring-and-weighted-signals.md)), the `derive_trend_direction()` function in `services/aggregation/worker.py` maps that numeric value to a `TrendDirection` enum. The rules are evaluated in a specific order, and the first matching rule wins:
1. **Mixed** — If the contradiction score exceeds `0.10` (the `MIXED_THRESHOLD` constant) *and* the absolute value of the average sentiment is below `0.30`, the direction is `MIXED`. This rule fires first because high contradiction with a weak directional signal indicates genuine disagreement in the evidence — the trend is not simply neutral, it is actively contested.
2. **Bullish** — If the average sentiment is `≥ 0.15` (the `BULLISH_THRESHOLD` constant), the direction is `BULLISH`. This means the weight-adjusted evidence leans positive with enough conviction to cross the threshold.
3. **Bearish** — If the average sentiment is `≤ -0.15` (the `BEARISH_THRESHOLD` constant), the direction is `BEARISH`. The symmetric threshold ensures that bullish and bearish classifications require the same magnitude of evidence.
4. **Neutral** — If none of the above conditions are met, the direction is `NEUTRAL`. This covers the range where the average sentiment falls between -0.15 and +0.15 without high contradiction — the evidence is either balanced or insufficient to establish a directional lean.
The mixed-first evaluation order is important. Consider a scenario where five documents are bullish and four are bearish, all with similar weights. The weighted sentiment average might be slightly positive (say, +0.08), which would normally map to neutral. But the contradiction score — computed from the minority/majority weight split — would be high (close to 0.44). The mixed rule catches this case: the evidence is not neutral, it is conflicted. This distinction matters downstream because mixed trends receive different treatment in the recommendation engine than neutral trends.
---
## Contradiction Detection
The contradiction detection module in `services/aggregation/contradiction.py` provides a structured analysis of disagreement within the signal set. Rather than collapsing contradictory evidence into a single number, it produces a `ContradictionResult` containing both an overall score and a list of `DisagreementDetail` objects that explain *where* the disagreement lies.
The `detect_contradictions()` function runs two analyses:
### Sentiment Disagreement
The `_detect_sentiment_disagreement()` function examines whether both positive and negative sentiment signals exist in the signal set. For each signal with a non-zero effective weight (`combined_weight × impact_score > 0`), it classifies the signal as positive or negative based on its `sentiment_value` and accumulates the effective weight for each side. If both sides have at least one signal, it produces a `DisagreementDetail` with dimension `"sentiment"`, listing the document IDs and weights for each side, along with a human-readable description like "Sentiment split: 3 positive vs 2 negative signals (minority weight ratio 38%)".
### Catalyst-Level Disagreement
The `_detect_catalyst_disagreement()` function goes deeper. It groups signals by their `catalyst_type` (earnings, product_launch, regulatory, etc.) using `CatalystEntry` objects built from the `document_impact_records`. Within each catalyst group, it checks whether both positive and negative signals exist. If they do, it produces a `DisagreementDetail` with dimension `"catalyst:<type>"` — for example, `"catalyst:earnings"` when some documents interpret an earnings report positively and others negatively. This catalyst-level analysis is valuable because it pinpoints the specific topic of disagreement rather than just flagging that disagreement exists somewhere in the evidence.
### The Overall Contradiction Score
The `_compute_overall_score()` function computes the backward-compatible scalar contradiction score using the minority/majority weight ratio formula:
```
contradiction_score = minority_weight / total_weight
```
where `minority_weight` is the smaller of the positive and negative effective weights, and `total_weight` is their sum. Signals with zero effective weight or neutral sentiment are excluded. The score ranges from `0.0` (complete agreement — all signals point the same direction) to `0.5` (perfect split — positive and negative weights are exactly equal). A score of `0.0` means no contradiction at all. A score above `0.10` combined with a weak average sentiment triggers the mixed direction classification in `derive_trend_direction()`.
The contradiction score also feeds directly into the confidence computation as a penalty, described in the next section. High contradiction reduces the system's confidence in the trend, which in turn affects whether the trend can escalate to actionable recommendations.
---
## Evidence Ranking
Not all documents contributing to a trend are equally important. The `rank_evidence()` function in `services/aggregation/worker.py` delegates to the evidence ranking module (`services/aggregation/evidence.py`) to produce ordered lists of the most influential supporting and opposing documents. The ranking uses a composite scoring approach configured by `EvidenceRankConfig`, considering multiple factors:
- **Weight** — the signal's composite weight from the scoring layer, reflecting recency, credibility, novelty, confidence, and market context.
- **Impact** — the extraction's impact score for the company, reflecting how significant the document's content is.
- **Recency** — how recently the document was published, with more recent documents ranked higher.
- **Confidence** — the extraction confidence, reflecting how reliably the LLM parsed the document.
Signals are split into supporting (positive sentiment) and opposing (negative sentiment) groups. Neutral and mixed sentiment signals are excluded from evidence lists — they do not argue for or against the trend direction. Within each group, signals are sorted by their composite rank score in descending order, and the top entries (up to `MAX_EVIDENCE_REFS = 10` per side) are returned as document ID lists.
The `assemble_trend_with_evidence()` function in `services/aggregation/worker.py` uses the detailed variant `rank_evidence_detailed()` to get `RankedEvidence` objects that include the individual scoring components (weight, impact, recency, confidence, sentiment value). These detailed rankings are persisted to the `trend_evidence` table for auditability, while the document ID lists are stored directly in the `TrendSummary` as `top_supporting_evidence` and `top_opposing_evidence`.
The evidence ranking serves two purposes. First, it provides the recommendation engine with the most relevant documents to cite in its thesis generation (see [Page 5](05-recommendation-generation.md)). Second, it gives human reviewers a quick way to understand *why* the system reached a particular trend assessment — the top-ranked documents are the ones that most influenced the direction and strength.
---
## Confidence Computation
The `compute_trend_confidence()` function in `services/aggregation/worker.py` produces the confidence score for a `TrendSummary`. This score is critical because it directly gates whether a trend can produce actionable recommendations — the eligibility evaluation in `services/recommendation/eligibility.py` requires a minimum confidence of `0.35` to generate any recommendation at all, and higher confidence thresholds control escalation to paper and live trading modes.
Confidence is computed from four components:
### Unique Source Count
The function counts the number of unique document IDs across all active signals (those with `combined_weight > 0`). This count is divided by 15 and capped at `0.8`:
```
count_factor = min(unique_sources / 15.0, 0.8)
```
A trend backed by 15 or more unique source documents reaches the maximum count contribution of `0.8`. A trend backed by a single document gets only `0.067`. This component rewards breadth of evidence — a trend confirmed by many independent sources is more trustworthy than one driven by a single article, regardless of how high that article's individual weight might be.
### Average Extraction Credibility
The average credibility weight across all active signals provides a baseline quality measure. If most contributing documents come from high-credibility sources, this component is high. If the evidence is dominated by low-credibility sources, confidence is penalized accordingly.
### Signal Agreement with Sample-Size Dampening
The agreement ratio measures what fraction of directional signals (bullish + bearish, excluding neutral) agree on the majority direction. If 8 out of 10 directional signals are bullish, the raw agreement is `0.8`. But raw agreement is misleading with small sample sizes — 1 out of 1 signals agreeing gives a perfect `1.0` agreement, which is not meaningful.
To address this, the agreement is dampened by a logarithmic sample-size factor:
```
agreement_dampener = min(1.0, log₂(unique_sources + 1) / log₂(8))
```
This dampener saturates at `1.0` when `unique_sources` reaches approximately 7 (since `log₂(8) = 3.0` and `log₂(8) = 3.0`). With fewer sources, the dampener reduces the agreement contribution: 1 source gives a dampener of `0.33`, 3 sources give `0.67`, and 7 sources give the full `1.0`. The log₂ scaling means that each additional source provides diminishing marginal improvement to the dampener, which matches the intuition that the jump from 1 to 3 sources is far more meaningful than the jump from 15 to 17.
### Contradiction Penalty
The contradiction score computed by `services/aggregation/contradiction.py` is applied as a direct penalty:
```
contradiction_penalty = contradiction_score × 0.4
```
A contradiction score of `0.5` (perfect split) produces a penalty of `0.2`, which is substantial enough to push a moderately confident trend below the eligibility threshold.
### The Combined Formula
The four components are combined as:
```
confidence = 0.3 × count_factor + 0.3 × avg_credibility + 0.4 × agreement contradiction_penalty
```
The result is clamped to `[0.0, 1.0]`. The weighting gives signal agreement the largest share (40%), reflecting the principle that consensus among diverse sources is the strongest indicator of a reliable trend. Source count and credibility each contribute 30%, providing a balanced assessment of evidence breadth and quality. The contradiction penalty can reduce confidence significantly — a highly contradicted trend with a score of 0.4 loses 0.16 points of confidence, which can easily drop it below the 0.35 eligibility gate.
---
## How Accumulating Signals Escalate Decisions
The trend direction, strength, and confidence computed by the aggregation engine are not just descriptive — they directly determine what action the system takes. The escalation path from passive observation to active trading is governed by the eligibility thresholds defined in `services/recommendation/eligibility.py`, and the key insight is that consecutive signals pointing in the same direction naturally strengthen the trend metrics that control this escalation.
### The Escalation Ladder
The `EligibilityConfig` dataclass in `services/recommendation/eligibility.py` defines the thresholds that map trend metrics to actions:
**Neutral (no recommendation).** A trend fails the eligibility gates entirely when confidence is below `0.35`, trend strength is below `0.10`, contradiction exceeds `0.60`, evidence count is below `2`, or the direction is neutral. The `_check_gates()` function evaluates these hard gates — if any gate fails, no recommendation is generated for that window.
**Watch.** A trend that passes the gates but has a direction of mixed, or has strength below `0.25` with confidence below `0.50`, maps to a `WATCH` action via `_determine_action()`. This is the system's way of saying "something is happening, but the evidence is not strong enough to act on." Watch recommendations are always `informational` mode — they are logged for human review but never trigger trades.
**Hold.** When the trend has a clear direction (bullish or bearish) but strength remains below `0.25` while confidence reaches `0.50` or above, the action maps to `HOLD`. This indicates that the directional signal is real but not yet strong enough for a position change. Like watch, hold recommendations are `informational` mode.
**Buy / Sell.** When trend strength reaches `0.25` or above with a bullish direction, the action is `BUY`. With a bearish direction at the same strength threshold, the action is `SELL`. These are the only actions that can escalate beyond informational mode — `_determine_mode()` evaluates whether the recommendation qualifies for `paper_eligible` (confidence ≥ `0.50`) or `live_eligible` (confidence ≥ `0.70`, contradiction ≤ `0.25`, evidence ≥ `5`).
### How Accumulation Drives Escalation
Consider a ticker that starts with no recent intelligence. The first bearish article arrives — a single document with negative sentiment. In the intraday window, this produces:
- **Trend strength** = `|avg_sentiment|` ≈ the absolute weighted sentiment from one signal, likely close to the impact score.
- **Confidence** = low, because `count_factor = min(1/15, 0.8) = 0.067` and the agreement dampener is only `log₂(2)/log₂(8) = 0.33`.
- **Direction** = bearish (if the weighted sentiment is ≤ -0.15).
With confidence well below `0.35`, this trend fails the eligibility gate entirely. No recommendation is generated. The system is in the neutral state.
A second bearish article arrives hours later. Now the intraday window has two signals:
- **Unique sources** = 2, so `count_factor = 0.133` and `agreement_dampener = log₂(3)/log₂(8) ≈ 0.53`.
- **Agreement** = `1.0 × 0.53 = 0.53` (both signals agree on bearish).
- **Confidence** ≈ `0.3 × 0.133 + 0.3 × avg_cred + 0.4 × 0.53` — likely around `0.35-0.45` depending on credibility.
If confidence crosses `0.35` and strength exceeds `0.10`, the trend passes the eligibility gates. But with strength below `0.25`, the action is `WATCH` or `HOLD` depending on confidence.
A third and fourth bearish article arrive over the next day. The 1-day window now has four agreeing signals:
- **Unique sources** = 4, so `count_factor = 0.267` and `agreement_dampener = log₂(5)/log₂(8) ≈ 0.77`.
- **Agreement** = `1.0 × 0.77 = 0.77`.
- **Confidence** ≈ `0.3 × 0.267 + 0.3 × avg_cred + 0.4 × 0.77` — likely `0.50-0.60`.
- **Strength** = `|avg_sentiment|` — with four bearish signals and no contradicting evidence, this could easily exceed `0.25`.
Now the trend maps to `SELL` with `paper_eligible` mode (confidence ≥ `0.50`). The system has escalated from no recommendation to a paper-eligible sell recommendation purely through the accumulation of consistent bearish evidence.
If the bearish evidence continues — more documents, more sources, higher credibility — confidence climbs further. At confidence ≥ `0.70` with contradiction ≤ `0.25` and evidence ≥ `5`, the recommendation reaches `live_eligible` mode, the highest escalation level.
The same process works in reverse for bullish accumulation: consecutive positive signals strengthen the bullish trend, increase confidence through source diversity and agreement, and escalate from watch through hold to buy.
### The Role of Contradiction in Preventing False Escalation
Accumulation only works when signals agree. If the fifth article about a ticker is bullish while the previous four were bearish, the contradiction score jumps — `minority_weight / total_weight` increases because the minority (bullish) side now has non-zero weight. This has two effects: the contradiction penalty reduces confidence (potentially dropping it below an eligibility threshold), and if the contradiction exceeds `0.10` with `|avg_sentiment| < 0.30`, the direction flips to mixed, which maps to `WATCH` regardless of strength. The system effectively de-escalates when the evidence becomes contested, requiring a clearer consensus before re-escalating.
---
## Trend Projections
After the `TrendSummary` is assembled and persisted, the aggregation engine computes a forward-looking `TrendProjection` via `compute_projection()` in `services/aggregation/projection.py`. Projections estimate where the trend is heading based on current momentum, macro signal decay, and upcoming catalysts. They are advisory — they do not directly trigger recommendations — but they provide valuable context for human reviewers and can inform future automated decision-making.
### Momentum
The `compute_trend_momentum()` function computes the rate of change in signed trend strength between the current and previous aggregation cycles. If the current window shows a bearish trend at strength `0.40` and the previous cycle showed bearish at `0.30`, the momentum is `-0.10` (strengthening bearish). If no previous data is available, the function uses a heuristic: momentum is estimated as half the current signed strength, providing a reasonable baseline for new trends.
Momentum enters the projection as a half-weighted adjustment to the current signed strength:
```
momentum_projected_signed = direction_sign × current_strength + momentum × 0.5
```
This means momentum influences the projection but does not dominate it — a strong current trend with weakening momentum still projects as directional, just with reduced strength.
### Macro Decay
The `project_macro_decay()` function estimates how active macro events will evolve over the projection horizon. Each macro event has an `estimated_duration` that maps to a decay half-life:
| Duration | Half-Life |
|----------|-----------|
| `short_term` | 1 day |
| `medium_term` | 7 days |
| `long_term` | 30 days |
For each event, the function computes the projected remaining impact at the end of the horizon using exponential decay: `future_factor = 2^(future_age_days / half_life)`. The impact is further scaled by a severity weight (`critical`: 1.0, `high`: 0.75, `moderate`: 0.5, `low`: 0.25). Positive and negative macro impacts are accumulated separately, and the projected macro direction is determined by comparing the two sides — bullish if positive exceeds negative by 20%, bearish if the reverse, mixed if both are present without a clear majority.
When the macro layer is enabled and macro events exist, the projection blends the company-specific momentum projection with the macro trajectory. The macro weight is capped at `0.4` (40% of the blended projection), ensuring that macro signals inform but do not overwhelm the company-specific trend. The blending formula combines the signed company projection with the signed macro projection:
```
blended = company_weight × momentum_projected + macro_weight × macro_signed
```
### Driving Factors
The projection records a list of human-readable driving factors that explain what is influencing the projected direction. These include momentum descriptions ("Positive momentum (+0.150) in recent trend strength"), macro impact projections ("Macro signals project bearish impact (strength 0.350) over 7d"), and upcoming catalysts drawn from the trend's `dominant_catalysts` list (limited to the top 3). If no specific factors are identified, a baseline continuation factor is recorded.
### Divergence Detection
After computing the projected direction, the function compares it to the current trend direction. If they differ — for example, the current trend is bearish but the projection is bullish due to decaying negative macro events and positive momentum — the projection is flagged with `diverges_from_current = True` and a divergence driving factor is appended. Divergence signals are particularly valuable because they indicate that the trend may be about to reverse, giving the recommendation engine and human reviewers an early warning.
The projection also flags low confidence when `projected_confidence` falls below the default threshold of `0.3`. Projection confidence starts at 80% of the current trend confidence (reflecting the inherent uncertainty of forward-looking estimates), with a small boost if macro data is available and a further reduction if the macro layer is disabled entirely.
---
## Persistence
Each aggregation cycle persists its results to four PostgreSQL tables, creating a durable record of the trend assessment and its supporting evidence.
### `trend_windows` — Current State
The `persist_trend_summary()` function in `services/aggregation/worker.py` upserts the `TrendSummary` into the `trend_windows` table, keyed by `(entity_type, entity_id, window)`. Each cycle overwrites the previous row for that ticker and window, so `trend_windows` always reflects the most recent assessment. The row includes the trend direction, strength, confidence, contradiction score, disagreement details (as JSON), supporting and opposing evidence document IDs (as JSON arrays), dominant catalysts, material risks, market context, and the generation timestamp.
### `trend_history` — Time-Series Snapshots
Immediately after the upsert, `persist_trend_summary()` also inserts a snapshot row into the `trend_history` table. Unlike `trend_windows`, this table is append-only — every aggregation cycle adds a new row, creating a time-series of how the trend evolved over time. The history table stores the direction, strength, confidence, contradiction score, catalysts, risks, and timestamp. This time-series data powers the trend charts in the dashboard and enables the momentum computation in `services/aggregation/projection.py` by providing the previous cycle's strength and direction. If the history insert fails (for example, if the table does not yet exist in a development environment), the failure is logged at debug level and does not block the main upsert.
### `trend_evidence` — Per-Document Rankings
The `persist_trend_evidence()` function writes detailed evidence ranking rows to the `trend_evidence` table, linked to the `trend_windows` row by its UUID. Each row records a document ID, its role (supporting or opposing), and the individual scoring components: rank score, weight component, impact component, recency component, confidence component, and sentiment value. Non-UUID document IDs (such as synthetic pattern signal IDs like `pattern:AAPL:earnings:7d`) are filtered out before insertion, since the `trend_evidence` table enforces a foreign key to the `documents` table.
### `trend_projections` — Forward-Looking Estimates
The `persist_trend_projection()` function in `services/aggregation/projection.py` inserts the `TrendProjection` into the `trend_projections` table, linked to the `trend_windows` row. The row stores the projected direction, strength, confidence, projection horizon, driving factors (as JSON), macro contribution percentage, divergence flag, and computation timestamp. Like trend history, projections accumulate over time, allowing analysis of how well the system's forward-looking estimates matched subsequent reality.
---
## What Comes Next
At this point, the aggregation engine has transformed weighted signals into `TrendSummary` objects across five time windows, detected contradictions, ranked evidence, computed confidence, and persisted everything to PostgreSQL. The trend metrics — direction, strength, confidence, contradiction score — encode the accumulated weight of evidence for each ticker. But a `TrendSummary` is still an assessment, not an action. The next stage translates these assessments into concrete recommendations: should the system buy, sell, hold, or simply watch? And with what conviction? [Page 5 — Recommendation Generation](05-recommendation-generation.md) explains how the recommendation engine applies data quality suppression, eligibility evaluation, position sizing, thesis generation, and risk classification to convert trend summaries into actionable `Recommendation` objects that the trading engine can execute.
@@ -0,0 +1,226 @@
# Page 5 — Recommendation Generation and Signal-to-Action Translation
The aggregation engine described in [Page 4](04-trend-aggregation-and-accumulating-signals.md) produces `TrendSummary` objects across five time windows for each ticker, encoding the direction, strength, confidence, contradiction level, and supporting evidence accumulated from all three signal layers. But a `TrendSummary` is an assessment — it describes what the evidence says, not what the system should do about it. The recommendation engine is where assessment becomes action. It takes each `TrendSummary`, subjects it to a series of deterministic evaluations, and produces a `Recommendation` object that specifies a concrete action (buy, sell, hold, or watch), an execution mode (informational, paper-eligible, or live-eligible), a position sizing guideline, a human-readable thesis, and a risk classification. Every decision in this pipeline is rule-based and fully traceable — the LLM is only involved in an optional downstream step that rewrites the thesis wording.
The recommendation worker in `services/recommendation/main.py` polls the `stonks:queue:recommendation` Redis queue for jobs, each specifying a ticker and time window. For each job, it delegates to `generate_recommendation()` in `services/recommendation/worker.py`, which orchestrates the full pipeline: fetch the latest trend summary, check for duplicate recommendations, fetch any available trend projection, evaluate data quality suppression, evaluate eligibility, optionally rewrite the thesis via LLM, build the `Recommendation` object, and persist everything to PostgreSQL. For a visual overview of this flow, see the [Recommendation Generation Flow diagram](diagrams/recommendation-generation-flow.md).
---
## Data Quality Suppression
Before the eligibility engine evaluates whether a trend is strong enough to act on, the suppression layer in `services/recommendation/suppression.py` asks a more fundamental question: is the underlying data reliable enough to act on at all? A trend might show high confidence and strong directionality, but if the documents feeding it are stale, poorly extracted, or drawn from a single source type, the apparent signal quality is illusory. The suppression layer acts as a pre-filter on data quality, running before the eligibility engine and forcing any recommendation built on unreliable data to `informational` mode regardless of how strong the trend metrics look.
The `evaluate_suppression()` function accepts a `TrendSummary` and a `DataQualityContext` — a set of metrics about the documents underlying the trend, populated by querying `documents` and `document_intelligence` tables for the evidence document IDs stored in the trend summary. When full document-level metrics are not available (for example, in a development environment without the full document pipeline), the function falls back to `build_quality_context_from_summary()`, which estimates quality metrics from the trend summary's own evidence counts and confidence.
### The Six Data Quality Checks
The suppression evaluation runs six independent checks, each comparing a data quality metric against a configurable threshold defined in `SuppressionConfig`. If any single check fails, the recommendation is suppressed:
1. **Low extraction confidence** — If the average extraction confidence across the evidence documents falls below `0.40` (`min_avg_extraction_confidence`), the underlying LLM extractions are too unreliable. This catches cases where the extractor struggled with document formatting, ambiguous content, or low-quality source material, as described in [Page 2](02-ai-agent-processing-and-extraction.md).
2. **Evidence staleness** — If the most recent evidence document is older than `168` hours (7 days, `max_evidence_staleness_hours`), the trend is based on outdated information. Markets move fast, and a week-old evidence base may no longer reflect current conditions. When documents exist but no timestamp is available, the evidence is conservatively treated as stale.
3. **Low source diversity** — If fewer than `1` distinct source type (`min_source_types`) contributed to the evidence, the signal may be driven by a single unreliable source class. In practice, this check fires when the quality context has documents but all come from the same source type (for example, all news articles with no filings or market data to corroborate).
4. **High extraction failure rate** — If more than `50%` (`max_extraction_failure_rate`) of the documents that should have contributed to the trend failed extraction entirely, the data pipeline is unreliable for this ticker. A high failure rate means the trend summary is built from a biased subset of the available evidence — the failed documents might have told a different story.
5. **Insufficient valid documents** — If fewer than `2` valid (non-failed) documents (`min_valid_documents`) contributed to the trend, there simply is not enough data to act on. A single document, no matter how high-quality, does not provide the corroboration needed for automated trading decisions.
6. **Low data quality score** — The `_compute_data_quality_score()` function computes an overall quality score from three weighted components: extraction confidence (40% weight, normalized against a 0.8 baseline), evidence freshness (30% weight, linear decay over the staleness window), and document coverage (30% weight, combining the valid/total ratio with a count factor that saturates at 10 documents). If this composite score falls below `0.30` (`min_data_quality_score`) and the low-confidence check has not already fired, a general suppression reason is added.
When any check triggers, the `SuppressionResult` records the specific reasons (as `SuppressionReason` enum values) and the computed data quality score. The worker in `services/recommendation/worker.py` uses this result to force the recommendation's mode to `informational` and append a suppression note to the thesis text, ensuring the suppression decision is visible in the audit trail.
### Safety Suppressions: Macro-Only and Pattern-Only Signals
Beyond the six data quality checks, two additional safety suppressions protect against acting on signals that lack company-specific corroboration:
**Macro-only suppression** (`evaluate_macro_only_suppression()`) fires when macro signals are the sole basis for a trend direction — no company-specific signals contributed at all. As described in [Page 3](03-signal-scoring-and-weighted-signals.md), macro signals enter the aggregation engine at a reduced weight of `0.3` relative to company signals. But even at reduced weight, macro signals alone can shift a trend direction if no company-specific evidence exists. When this happens, the recommendation is forced to `informational` mode with a caveat noting that the signal is macro-only and should not be used for automated trading.
**Pattern-only suppression** (`evaluate_pattern_only_suppression()`) applies the same logic to competitive/pattern signals. When pattern-based signals from `services/aggregation/pattern_matcher.py` and `services/aggregation/signal_propagation.py` are the sole contributors — no company-specific or macro signals — the recommendation is suppressed. Historical patterns are valuable context, but acting on them without any current evidence is too speculative for automated trading.
Both safety suppressions are evaluated in the worker after the main suppression check, and both force the mode to `informational` when triggered.
---
## Eligibility Evaluation
Recommendations that survive the suppression layer enter the eligibility evaluation in `services/recommendation/eligibility.py`. This is the core decision logic — a set of deterministic rules that map trend metrics to actions, execution modes, and position sizing. The `evaluate_eligibility()` function is the single entry point, accepting a `TrendSummary` and an `EligibilityConfig` of tunable thresholds.
### Gate Checks
The `_check_gates()` function applies five hard gates. If any gate fails, the trend is ineligible for a recommendation (though the action and mode are still computed for the audit trace):
| Gate | Threshold | Rejection Reason |
|------|-----------|-----------------|
| Confidence | ≥ `0.35` | `low_confidence` |
| Trend strength | ≥ `0.10` | `low_trend_strength` |
| Contradiction score | ≤ `0.60` | `high_contradiction` |
| Evidence count | ≥ `2` (supporting + opposing) | `insufficient_evidence` |
| Direction | ≠ `neutral` | `neutral_direction` |
These gates are intentionally conservative. A confidence threshold of `0.35` means the system needs meaningful evidence breadth and agreement before generating any recommendation at all (see the confidence computation in [Page 4](04-trend-aggregation-and-accumulating-signals.md)). The contradiction ceiling of `0.60` allows moderately contested trends through — only when the evidence is deeply split does the gate reject. The evidence minimum of `2` ensures that no recommendation is ever based on a single document.
When a trend fails any gate, the resulting `EligibilityResult` has `eligible = False` and the mode is forced to `informational`, regardless of what the mode escalation logic would otherwise compute.
### Action Mapping
The `_determine_action()` function maps the trend's direction and strength to one of four action types. The logic evaluates in a specific order:
**Mixed or neutral direction → WATCH.** If the trend direction is `mixed` (high contradiction with weak directional signal) or `neutral`, the action is always `WATCH`. There is no directional conviction to act on.
**Strong directional signal → BUY or SELL.** If the trend strength reaches `0.25` or above (`action_strength_threshold`), the action follows the direction: `BUY` for bullish, `SELL` for bearish. This threshold ensures that only trends with meaningful magnitude trigger position-changing actions.
**Weak directional signal with decent confidence → HOLD.** If the trend has a clear direction (bullish or bearish) but strength remains below `0.25`, the action depends on confidence. If confidence reaches `0.50` or above (`hold_confidence_threshold`), the action is `HOLD` — the system recognizes the directional lean but does not have enough conviction to recommend a position change. Below `0.50` confidence, the action falls to `WATCH`.
This mapping creates the escalation ladder described in [Page 4](04-trend-aggregation-and-accumulating-signals.md): as consecutive signals accumulate and strengthen the trend metrics, the action naturally progresses from WATCH → HOLD → BUY/SELL.
### Mode Escalation
The `_determine_mode()` function determines the highest execution mode allowed for the recommendation. Mode controls whether the recommendation is purely informational, eligible for paper trading, or eligible for live trading:
**WATCH and HOLD → always informational.** These actions do not trigger trades, so they are always `informational` mode. They are logged for human review and dashboard display but never enter the trading engine.
**BUY and SELL → escalation based on signal quality.** For actionable recommendations, mode escalates through three tiers:
- **`informational`** — The default when confidence is below `0.50`. The recommendation is recorded but not eligible for any trading.
- **`paper_eligible`** — When confidence reaches `0.50` or above (`paper_confidence_threshold`). The recommendation can be picked up by the paper trading engine described in [Page 6](06-trading-decisions-and-execution.md).
- **`live_eligible`** — The strictest tier, requiring confidence ≥ `0.70` (`live_confidence_threshold`), contradiction ≤ `0.25` (`live_max_contradiction`), and evidence count ≥ `5` (`live_min_evidence`). This triple gate ensures that only high-conviction, well-corroborated, low-contradiction recommendations can trigger live trades.
The evidence count for mode escalation is computed as the sum of supporting and opposing evidence documents, matching the same count used in the gate checks.
---
## Position Sizing
The `_compute_position_sizing()` function in `services/recommendation/eligibility.py` translates signal quality into a portfolio allocation guideline. Position sizing is not a fixed value — it scales dynamically with the confidence and strength of the underlying trend, penalized by contradiction and thin evidence.
### Base and Scaling
The computation starts with a base portfolio allocation of `1%` (`base_portfolio_pct = 0.01`) and scales upward based on two factors:
- **Confidence factor** — `0.8 × confidence` (`confidence_sizing_weight`), reflecting how much the system trusts the trend assessment.
- **Strength factor** — `0.5 + 0.5 × trend_strength`, ranging from `0.5` (weakest trend) to `1.0` (strongest trend).
The raw portfolio percentage is computed as:
```
raw_portfolio = base + confidence_factor × strength_factor × (max - base)
```
where `max` is `10%` (`max_portfolio_pct = 0.10`). At maximum confidence (1.0) and maximum strength (1.0), the raw allocation reaches the full 10%. At typical values (confidence 0.6, strength 0.3), the raw allocation is considerably lower.
### Contradiction Penalty
The contradiction score applies a multiplicative penalty:
```
portfolio_pct = raw_portfolio × (1.0 0.5 × contradiction_score)
```
A contradiction score of `0.40` reduces the allocation by 20%. A score of `0.0` (no contradiction) applies no penalty. This ensures that contested trends receive smaller position sizes even when they pass the eligibility gates.
### Evidence Count Penalty
Thin evidence further reduces the allocation:
- Fewer than `3` evidence documents → multiply by `0.5` (halved).
- Fewer than `5` evidence documents → multiply by `0.75`.
- `5` or more documents → no penalty.
This penalty stacks with the contradiction penalty, so a trend with high contradiction and thin evidence receives a substantially reduced position size.
### Max Loss Scaling
The same scaling logic applies to the maximum loss percentage, which starts at a base of `0.3%` (`base_max_loss_pct = 0.003`) and scales up to `2%` (`max_max_loss_pct = 0.02`). Higher-conviction positions are allowed larger loss tolerances, while low-conviction or contested positions are constrained to tighter stops.
The final `PositionSizing` object (defined in `services/shared/schemas.py`) contains `portfolio_pct` and `max_loss_pct`, both clamped to their respective bounds. This object is embedded in the `Recommendation` and later consumed by the trading engine's own position sizer (described in [Page 6](06-trading-decisions-and-execution.md)), which applies additional portfolio-level constraints.
---
## Thesis Generation
Every recommendation includes a human-readable thesis that explains the reasoning behind the action. Thesis generation happens in two layers: a deterministic assembly that is always present, and an optional LLM rewrite that polishes the wording for trading-eligible recommendations.
### Deterministic Thesis Assembly
The `build_thesis()` function in `services/recommendation/worker.py` constructs a thesis string entirely from the trend data and eligibility result, with no model involvement. The thesis is assembled from several components in order:
1. **Opening** — States the ticker, trend direction, window, strength, and confidence. For example: "AAPL shows a bearish trend over the 7d window with strength 0.35 and confidence 0.62."
2. **Catalysts** — Lists the top three dominant catalysts from the `TrendSummary`, drawn from the evidence ranking described in [Page 4](04-trend-aggregation-and-accumulating-signals.md).
3. **Contradiction note** — If the contradiction score exceeds `0.15`, a note flags the signal disagreement and its magnitude.
4. **Trend projection** — When a `TrendProjection` is available and not flagged as low-confidence, the thesis incorporates the projected direction, strength, and top driving factors. If the projection diverges from the current trend, a divergence note is appended.
5. **Risks** — Lists the top two material risks from the `TrendSummary`.
6. **Evidence count** — States the number of supporting and opposing evidence documents.
7. **Prescriptive action** — States the recommended action and mode (e.g., "Recommendation: SELL (paper eligible).").
The deterministic thesis is always generated and serves as the audit reference. Even when the LLM rewrites the thesis, the deterministic version is preserved in the model metadata for traceability.
### Optional LLM Rewrite via the Thesis-Rewriter Agent
For recommendations that are both eligible and not suppressed, the worker optionally invokes the thesis-rewriter agent to polish the deterministic thesis into analyst-quality prose. The LLM rewrite is implemented in `services/recommendation/thesis_llm.py` and uses the `thesis-rewriter` agent slug, resolved at runtime through the `AgentConfigResolver` in `services/shared/agent_config.py`.
The `AgentConfigResolver` queries the `ai_agents` and `agent_variants` database tables to resolve the active configuration for the `thesis-rewriter` slug, preferring an active variant's model, timeout, and retry settings when one exists. The resolver uses a 60-second TTL in-memory cache to avoid hitting the database on every recommendation. This is the same resolution mechanism used by the document extractor and event classifier agents described in [Page 2](02-ai-agent-processing-and-extraction.md).
The `rewrite_thesis_with_llm()` function builds a prompt from the deterministic thesis and trend context (ticker, window, direction, strength, confidence, contradiction score, catalysts, risks), sends it to the local Ollama instance via HTTP, and returns the rewritten text. The system prompt enforces strict rules: no fabricated information, no numbers or facts not present in the input, under 150 words, neutral professional tone, and only the rewritten thesis text in the response.
The LLM layer is purely additive — if the call fails for any reason (network error, timeout, empty response, token budget exceeded), the original deterministic thesis is returned unchanged. The worker in `services/recommendation/main.py` resolves the thesis-rewriter configuration at startup and refreshes it every 50 jobs to pick up configuration changes without requiring a restart. When no database configuration exists for the `thesis-rewriter` slug, thesis rewriting is silently disabled.
Performance logging for the thesis-rewriter is written to the `agent_performance_log` table, recording success/failure, duration, estimated token counts, and the variant ID. Token budget enforcement checks hourly usage against the variant's configured budget before making the LLM call, preventing runaway costs from high-volume recommendation cycles.
### Risk Classification Prefix
Before the thesis is stored, the `classify_risk()` function in `services/recommendation/worker.py` assigns a risk classification label that is prepended to the thesis text as a `[risk:<level>]` prefix. The classification is computed from a composite score:
| Factor | Contribution |
|--------|-------------|
| Contradiction score | `contradiction × 2.0` |
| Low confidence | `(1.0 confidence) × 1.5` |
| Low evidence count | `+1.0` if < 3 docs, `+0.5` if < 5 docs |
| Rejection reasons | `+0.5` per rejection reason |
The composite score maps to four levels:
| Score Range | Classification |
|-------------|---------------|
| ≥ 3.0 | `very_high` |
| ≥ 2.0 | `high` |
| ≥ 1.0 | `moderate` |
| < 1.0 | `low` |
A recommendation with high contradiction (0.4 → contributes 0.8), moderate confidence (0.55 → contributes 0.675), and 4 evidence documents (contributes 0.5) would score 1.975, classifying as `moderate`. The same recommendation with only 2 evidence documents would score 2.475, pushing it to `high`. This classification gives downstream consumers — both the trading engine and human reviewers — a quick risk signal without needing to re-evaluate the underlying metrics.
---
## Persistence
The recommendation pipeline persists its output to three PostgreSQL tables, creating a complete audit trail from trend assessment through decision logic to the final recommendation.
### `recommendations` — The Core Record
The `persist_recommendation()` function in `services/recommendation/worker.py` inserts the `Recommendation` into the `recommendations` table. Each row captures the ticker, action, mode, confidence, time horizon, thesis (including the risk classification prefix and any suppression notes), invalidation conditions (as JSONB), position sizing (portfolio percentage and max loss percentage), model metadata (provider, model name, prompt version, schema version), risk classification, and generation timestamp. The insert returns the recommendation's UUID, which serves as the foreign key for the evidence and risk evaluation tables.
### `recommendation_evidence` — Evidence Citations
For each evidence document referenced in the recommendation, a row is inserted into the `recommendation_evidence` table linking the recommendation UUID to the document UUID, with an evidence type (`supporting` or `opposing`) and a position-based weight that decays with rank: `weight = 1.0 / (1.0 + index × 0.1)`. The first supporting document gets weight `1.0`, the second gets `0.91`, the third `0.83`, and so on. Non-UUID document IDs (such as synthetic pattern signal IDs like `pattern:AAPL:earnings:7d` from the competitive signal layer) are filtered out before insertion, since the table enforces a foreign key to the `documents` table.
### `risk_evaluations` — Decision Audit Trail
The `risk_evaluations` table records the full eligibility decision for each recommendation: whether the trend was eligible, the allowed mode, the list of rejection reasons (as JSONB), and a `risk_checks` JSONB object containing the time horizon, position sizing details, invalidation conditions, and risk classification. This table enables post-hoc analysis of why the system made a particular decision — auditors can trace from the recommendation back through the eligibility evaluation to the underlying trend metrics.
---
## Deduplication
Before running the full evaluation pipeline, the worker checks whether the latest recommendation for the same ticker and time horizon is effectively identical to what would be generated. The `_is_duplicate_recommendation()` function in `services/recommendation/worker.py` compares the previous recommendation's action, mode, and confidence (within a `0.01` tolerance) against the current eligibility result. If all three match, the recommendation is skipped — the underlying trend data has not changed meaningfully since the last cycle. This prevents the system from flooding the `recommendations` table with identical entries on every aggregation cycle, while still generating a new recommendation whenever the trend metrics shift enough to change the action, mode, or confidence.
---
## What Comes Next
At this point, the recommendation engine has translated trend assessments into concrete `Recommendation` objects — each with an action, execution mode, position sizing guideline, thesis, and risk classification — and persisted them alongside their evidence citations and eligibility audit trails. Recommendations marked as `paper_eligible` or `live_eligible` are now available for the trading engine to consume. [Page 6 — Trading Decisions and Execution](06-trading-decisions-and-execution.md) explains how the trading engine polls these recommendations, applies its own pre-trade check sequence (circuit breakers, trading windows, confidence gates, deduplication, declining positions, and max open positions), computes final position sizes with portfolio-level constraints, and submits orders through the broker adapter to Alpaca's paper trading API.
@@ -0,0 +1,199 @@
# Page 6 — Trading Decisions and Execution
The recommendation engine described in [Page 5](05-recommendation-generation.md) produces `Recommendation` objects with an action, execution mode, position sizing guideline, thesis, and risk classification. Recommendations marked as `paper_eligible` or `live_eligible` are persisted to the `recommendations` table and are now available for the final stage of the pipeline: autonomous trade execution. The trading engine in `services/trading/engine.py` is where intelligence becomes action. It polls eligible recommendations, subjects each one to a strict sequence of pre-trade safety checks, computes a portfolio-aware position size, and — if every gate passes — submits an order through the broker adapter to Alpaca's paper trading API. Every evaluation, whether it results in a trade or a skip, is recorded as a `TradingDecision` in the `trading_decisions` table, creating a complete audit trail from the original document signal through to the broker response.
For a visual overview of the decision flow, see the [Trading Engine Decision Loop diagram](diagrams/trading-engine-decision-loop.md).
---
## The Trading Engine Decision Loop
The `TradingEngine` class in `services/trading/engine.py` is the orchestrator. When `start()` is called, it loads the current portfolio state from PostgreSQL — open positions, reserve pool balance, sector exposure, portfolio heat — and then spawns five concurrent `asyncio` tasks that run for the lifetime of the engine:
1. **`_decision_loop()`** — The core polling loop. Every 60 seconds (configurable via `polling_interval_seconds`), it queries the `recommendations` table for rows where `action IN ('buy', 'sell')`, `mode IN ('paper_eligible', 'live_eligible')`, and `generated_at` is within the last two hours. Recommendations are ordered by confidence descending and capped at 50 per cycle. For each recommendation, the engine fetches the current market price (first from `market_snapshots`, falling back to the Polygon API), then runs the full pre-trade evaluation pipeline described below.
2. **`_stop_loss_monitor()`** — Periodically checks current prices against the stop-loss and take-profit levels maintained by the `StopLossManager` in `services/trading/stop_loss_manager.py`. When a price crosses a stop-loss or take-profit threshold, the monitor submits a sell order to the broker queue. The `StopLossManager` computes initial levels from ATR and risk tier parameters, re-evaluates them when volatility shifts materially (ATR change > 10%), activates trailing stops when the price moves more than 50% toward the take-profit target, and tightens stops proactively when portfolio heat exceeds 80% of the maximum.
3. **`_performance_loop()`** — Computes portfolio-wide performance metrics (total value, unrealized and realized P&L, win rate, Sharpe ratio, drawdown, portfolio heat), persists daily snapshots to `portfolio_snapshots`, checks for daily-loss circuit breaker triggers, evaluates profit-taking opportunities, and synchronizes positions with the database to detect closed positions and trigger reserve pool siphoning.
4. **`_risk_tier_scheduler()`** — Runs once daily at 16:00 ET (market close). It loads the latest `PerformanceMetrics` from `portfolio_snapshots`, computes the reserve pool as a fraction of total portfolio value, and delegates to the `RiskTierController` in `services/trading/risk_tier_controller.py` to determine whether the active risk tier should change. Tier changes are persisted to `risk_tier_history` and take effect immediately for subsequent decision cycles.
5. **`_rebalance_scheduler()`** — Runs weekly on Monday at 09:45 ET (shortly after market open). It loads current positions, evaluates them against the active risk tier's constraints using the `PortfolioRebalancer`, and pushes any rebalance sell orders to `stonks:queue:broker_orders`. The rebalancer respects the circuit breaker — if any breaker is active, the rebalance cycle is skipped entirely.
All five tasks run concurrently within a single `asyncio` event loop. Graceful shutdown via `stop()` cancels all tasks and awaits their completion. If any task encounters an unexpected exception, it logs the error and retries after a brief sleep rather than crashing the engine.
---
## Pre-Trade Check Sequence
When the decision loop picks up a buy recommendation, it calls `evaluate_recommendation()` — a synchronous method that runs the full pre-trade check sequence. The checks are applied in a strict order, and the first failure short-circuits the evaluation with a `skip` decision. This fail-fast design ensures that expensive downstream computations (like position sizing and correlation analysis) are never reached when a simple gate would have rejected the trade.
The six checks, in order:
**a. Circuit breaker check.** The engine calls `self.circuit_breaker.is_active()` on the current `CircuitBreakerState`. If any circuit breaker is active and its cooldown has not expired, the recommendation is skipped with reason `circuit_breaker_active`. The circuit breaker mechanism is described in detail below.
**b. Trading window check.** The `is_within_trading_window()` function verifies that the current time falls within US market hours. Outside the trading window, no orders are submitted — the recommendation is skipped with reason `outside_trading_window`.
**c. Confidence gate.** The recommendation's confidence score is compared against the active risk tier's `min_confidence` threshold. A conservative tier requires confidence ≥ 0.75, moderate requires ≥ 0.55, and aggressive requires ≥ 0.40. If the recommendation's confidence falls below the tier minimum, it is skipped with reason `insufficient_confidence`. This gate ensures that the risk tier's conservatism is enforced before any capital allocation is considered.
**d. Deduplication check.** The engine maintains an in-memory set of processed recommendation IDs (`processed_recommendation_ids`) and also checks Redis via `stonks:dedupe:trading:*` keys (with a 24-hour TTL). If the recommendation has already been evaluated in this engine session or by a previous instance, it is skipped with reason `duplicate_recommendation`. This prevents the same recommendation from generating multiple orders across polling cycles.
**e. Declining positions check.** The `check_declining_positions()` method examines all open positions. If more than 50% of positions have unrealized losses exceeding 2% of their entry value, the engine halts new entries with reason `multiple_declining_positions`. This is a portfolio-level safety valve — when the majority of existing positions are underwater, adding new exposure compounds the risk.
**f. Max open positions check.** The engine enforces a configurable maximum number of concurrent positions (default 10). If the portfolio is already at capacity, the recommendation is skipped with reason `max_positions_reached`.
For sell recommendations, the engine follows a separate, simpler path: it verifies the trading window, looks up the existing position for the ticker, and submits a market sell order for the full position quantity without running the position sizer. Sell decisions still generate a `TradingDecision` audit record and set the Redis deduplication key.
If all six checks pass for a buy recommendation, the engine proceeds to position sizing.
---
## Position Sizing
The `PositionSizer` in `services/trading/position_sizer.py` translates a recommendation's signal quality into a concrete dollar amount and share count, applying a sequential pipeline of adjustments that account for confidence, portfolio composition, sector concentration, correlation, and upcoming earnings events. The sizer operates on the *active pool* — the portion of the portfolio available for trading after subtracting the reserve pool balance.
### Base Sizing
The computation begins with a base allocation percentage derived from the risk tier:
```
base_allocation_pct = risk_tier.max_position_pct × 0.5
raw_pct = base_allocation_pct × (confidence / min_confidence)
```
The base starts at half the tier's maximum position percentage, then scales linearly with how far the recommendation's confidence exceeds the tier minimum. A moderate-tier recommendation with confidence 0.70 against a minimum of 0.55 would produce a raw percentage of `0.05 × (0.70 / 0.55) ≈ 0.0636`, or about 6.4% of the active pool. The raw percentage is clamped to `max_position_pct` (5% for conservative, 10% for moderate, 15% for aggressive) and then converted to a dollar amount against the active pool. An absolute position cap (default $50) provides a hard ceiling regardless of pool size — a safety measure for the paper trading environment.
### Correlation-Aware Diversification
The sizer computes a weighted average correlation between the candidate ticker and all existing positions, using the pairwise correlation matrix that the engine refreshes from 30 days of daily close prices in `market_snapshots`. Each existing position's correlation is weighted by its market value, so larger positions have more influence on the diversification check.
If the weighted average correlation exceeds 0.8, the position is rejected outright — the portfolio already has too much exposure to correlated assets. Between 0.5 and 0.8, the dollar amount is reduced proportionally: a correlation of 0.65 produces a scale factor of `1.0 (0.65 0.5) / (0.8 0.5) = 0.5`, halving the position size. Below 0.5, no reduction is applied.
### Sector Exposure Reduction
The sizer checks whether adding the new position would push the sector's total exposure beyond the risk tier's `max_sector_pct` (20% for conservative, 30% for moderate, 40% for aggressive). If the sector is already at its limit, the position is rejected. If the new position would exceed the limit, the dollar amount is reduced to exactly fill the remaining sector capacity.
### Diversification Bonus
When the portfolio holds fewer than three distinct sectors and the candidate ticker belongs to a new sector, the sizer applies a 1.2× bonus to the dollar amount. This incentivizes early diversification — the first few positions are encouraged to spread across sectors rather than concentrating in a single one. The bonus is re-clamped to `max_position_pct` after application to prevent oversized positions.
### Earnings Proximity Adjustment
The sizer checks the earnings calendar for the candidate ticker. If earnings are within one trading day, the position is rejected entirely — the binary risk of an earnings surprise is too high for automated entry. If earnings are within three trading days, the dollar amount is reduced by 50%. Beyond three days, no adjustment is applied.
### Portfolio Heat Check and Share Rounding
After all adjustments, the sizer estimates the new position's contribution to portfolio heat (the aggregate risk from stop-loss distances across all positions). If adding the position would push total heat beyond `max_portfolio_heat × active_pool` (10% for conservative, 20% for moderate, 30% for aggressive), the position is rejected.
Finally, the dollar amount is converted to whole shares via `floor(dollar_amount / current_price)`. If rounding produces zero shares (the position is too small for even one share at the current price), the position is rejected. The final dollar amount is recalculated from the whole-share quantity to reflect the actual capital deployed.
The `PositionSizeResult` returned to the engine includes the dollar amount, share quantity, allocation percentage, a list of human-readable adjustment notes, and a rejected flag with reason if any step failed. These adjustment notes are embedded in the `TradingDecision`'s `decision_trace` for full auditability.
---
## Circuit Breaker
The `CircuitBreaker` in `services/trading/circuit_breaker.py` is a pure computation module that evaluates three independent trigger conditions. It carries no state of its own — the engine manages the `CircuitBreakerState` dataclass and persists trigger events to the `circuit_breaker_events` table and Redis keys under `stonks:trading:circuit_breaker:*`.
### Three Trigger Types
**Daily loss trigger.** When the portfolio's daily P&L loss exceeds 5% of total portfolio value (`daily_loss_pct = 0.05`), the circuit breaker activates. The `check_daily_loss()` method compares the absolute loss ratio against the threshold. The cooldown duration is set to `volatility_pause_hours` (default 2 hours). The performance loop in the engine calls `_check_circuit_breaker_daily_loss()` periodically to evaluate this condition against the latest portfolio metrics. In extreme cases where the drawdown exceeds an emergency threshold, the reserve pool's emergency liquidation mechanism may also be triggered.
**Single position loss trigger.** When any individual position loses more than 15% of its entry value (`single_position_loss_pct = 0.15`), the circuit breaker activates with a ticker-specific cooldown. The `check_single_position()` method evaluates the loss percentage. The cooldown for the affected ticker is set to `ticker_cooldown_hours` (default 48 hours), during which the engine will not re-enter that ticker. The `is_ticker_cooled_down()` method checks whether a specific ticker is still within its cooldown window by consulting the `ticker_cooldowns` dictionary in the `CircuitBreakerState`.
**Volatility trigger (stop-loss clustering).** When three or more stop-losses fire within a 30-minute rolling window (`stop_loss_hits_threshold = 3`, `stop_loss_window_minutes = 30`), the circuit breaker activates. The `check_volatility()` method uses a sliding window algorithm: it sorts the stop-loss timestamps and checks every contiguous subsequence of length `stop_loss_hits_threshold` to see if it fits within the window. This detects rapid-fire stop-loss cascades that indicate extreme market volatility. The cooldown is `volatility_pause_hours` (default 2 hours).
### Cooldown Computation
The `compute_cooldown_expiry()` method calculates when a triggered breaker expires. For `daily_loss` and `volatility` triggers, the expiry is `triggered_at + volatility_pause_hours`. For `single_position` triggers, the expiry is `triggered_at + ticker_cooldown_hours`, giving the affected ticker a longer cooling-off period. The `is_active()` method returns `True` when the breaker is flagged active and the current time has not yet passed the cooldown expiry.
### Redis State Tracking
The engine persists circuit breaker state to Redis under the `stonks:trading:circuit_breaker:*` key pattern (constructed by `trading_cb_key()` in `services/shared/redis_keys.py`). Each trigger type gets its own key — for example, `stonks:trading:circuit_breaker:daily_loss` — storing the activation timestamp and cooldown expiry. This allows the state to survive engine restarts and enables external monitoring tools to query breaker status without accessing the engine's memory.
---
## Reserve Pool
The `ReservePoolController` in `services/trading/reserve_pool.py` manages an untouchable cash reserve that grows from realized trading profits. The reserve serves two purposes: it provides a buffer against drawdowns, and its size relative to the portfolio influences risk tier upgrade decisions.
### Profit Siphoning
When the engine detects a closed position with positive unrealized P&L (via `_sync_positions_and_siphon()` in the performance loop), it calls `siphon_profit()` on the controller. The method transfers a configurable fraction of the realized profit into the reserve — by default 20% (`siphon_pct = 0.20`). Only positive profits are siphoned; losses do not reduce the reserve balance. Each siphon event is recorded in the `reserve_pool_ledger` table with the transfer amount, resulting balance, trigger type (`profit_siphon`), the ticker as reference, and a timestamp.
### High-Water Mark Rebalancing
The `is_high_water()` method returns `True` when the reserve balance exceeds 30% of total portfolio value (`high_water_pct = 0.30`). This signal is consumed by the risk tier scheduler — when the reserve is healthy and other performance criteria are met, the controller may recommend upgrading to a more aggressive tier. The high-water mark acts as a confidence indicator: a large reserve means the system has been consistently profitable and can afford to take on more risk.
### Emergency Liquidation
The `should_emergency_liquidate()` method checks whether the current drawdown exceeds an emergency threshold. When triggered, `emergency_liquidate()` returns the full reserve balance for release back into the active pool. The caller (the engine) is responsible for zeroing the persisted balance and recording the ledger entry. Emergency liquidation is a last resort — it sacrifices the safety buffer to prevent the portfolio from hitting a catastrophic loss level.
### Active Pool Computation
The `compute_active_pool()` method calculates the capital available for trading: `active_pool = total_portfolio_value reserve_balance`. All position sizing computations use the active pool rather than the total portfolio value, ensuring that the reserve is never inadvertently deployed into new positions.
---
## Risk Tier Auto-Adjustment
The `RiskTierController` in `services/trading/risk_tier_controller.py` evaluates portfolio performance and determines whether the active risk tier should shift. The system supports three tiers — conservative, moderate, and aggressive — each defined by a `RiskTierConfig` dataclass in `services/trading/models.py` with distinct parameter values:
| Parameter | Conservative | Moderate | Aggressive |
|-----------|-------------|----------|------------|
| `min_confidence` | 0.75 | 0.55 | 0.40 |
| `max_position_pct` | 5% | 10% | 15% |
| `stop_loss_atr_multiplier` | 1.5× | 2.0× | 2.5× |
| `reward_risk_ratio` | 2.0 | 1.5 | 1.2 |
| `max_sector_pct` | 20% | 30% | 40% |
| `max_portfolio_heat` | 10% | 20% | 30% |
The tier controller's `evaluate()` method checks two conditions:
**Downgrade (any one triggers).** If the trailing 30-day win rate drops below 40% or the current drawdown exceeds 15%, the tier steps down by one level (e.g., aggressive → moderate). If the system is already at conservative, no further downgrade is possible.
**Upgrade (all must be true).** If the win rate exceeds 55%, the reserve pool exceeds 20% of total portfolio value, and the current drawdown is below 5%, the tier steps up by one level. The triple requirement ensures that upgrades only happen when the system is performing well, has built a safety cushion, and is not in a drawdown.
The risk tier scheduler in the engine evaluates these conditions daily at market close. When a tier change occurs, it is persisted to the `risk_tier_history` table with the previous tier, new tier, trigger source (`auto_adjustment`), and the metrics that drove the decision (win rate, drawdown, reserve percentage, Sharpe ratio). The new tier takes effect immediately — the engine updates its `_active_risk_tier` reference, and all subsequent decision cycles use the new tier's parameters for confidence gates, position sizing, stop-loss computation, and sector exposure limits.
---
## Order Submission Flow
When `evaluate_recommendation()` returns an `act` decision, the engine constructs an order job and pushes it through a multi-stage submission pipeline that spans two services.
### TradingDecision Persistence
Every evaluation — whether it results in `act` or `skip` — produces a `TradingDecision` dataclass that is persisted to the `trading_decisions` table via `_persist_decision()`. The record captures the recommendation ID, decision outcome, skip reason (if applicable), ticker, computed position size and share quantity, the risk tier at the time of decision, portfolio heat, active pool and reserve pool balances, circuit breaker status, correlation and sector exposure check results, earnings proximity flag, and a `decision_trace` JSONB field containing the full reasoning chain. This creates a complete audit record of every recommendation the engine evaluated and why it acted or declined.
### Order Enqueue
For `act` decisions, the engine builds an order job dictionary containing the trading decision ID, ticker, action (buy or sell), quantity, and order type (market). This job is pushed via `rpush` to the `stonks:queue:broker_orders` Redis queue (constructed by `queue_key(QUEUE_BROKER)` from `services/shared/redis_keys.py`). The engine immediately deducts the estimated order cost from the in-memory active pool to prevent over-allocation across concurrent recommendation evaluations within the same polling cycle.
### Broker Service Processing
The broker service in `services/adapters/broker_service.py` runs as a standalone worker that polls `stonks:queue:broker_orders` via `blpop`. For each order job, `process_order_job()` executes a multi-step pipeline:
1. **Idempotency check.** A deterministic idempotency key is generated from the job's ticker, action, quantity, and trading decision ID. The service checks Redis first (fast path) and then the `orders` table (durable fallback) to prevent duplicate submissions. If a matching key exists, the job is silently dropped.
2. **Risk evaluation.** The service loads the current `PortfolioRiskConfig` from the database and the account's risk state (open positions, daily P&L, sector exposure) from both the database and the Alpaca API. The `evaluate_order()` function runs the proposed order through a set of risk checks — position limits, sector concentration, daily loss thresholds — and produces an evaluation result. The evaluation is persisted to the `risk_evaluations` table regardless of outcome.
3. **Alpaca submission.** If the risk evaluation passes, the service calls `submit_order()` on the `AlpacaBrokerAdapter` in `services/adapters/broker_adapter.py`. The adapter constructs the Alpaca REST API payload (symbol, quantity, side, order type, time in force) and submits it to `paper-api.alpaca.markets/v2/orders` with an idempotency key header. The adapter follows a fail-closed policy: any network error or ambiguous response returns a rejected `OrderResponse` rather than risking duplicate orders.
4. **Persistence and audit trail.** The `persist_order()` function writes the order to the `orders` table with the full request and response details, risk evaluation results, and the recommendation ID for traceability. When the order is filled, the fill details (price, quantity) are recorded. Order events are published to the analytical lakehouse via MinIO for downstream analysis. The Redis idempotency marker is set after successful persistence to prevent reprocessing.
The result is a complete chain of custody: from the original document that produced a signal (Pages [1](01-data-ingestion-and-preparation.md)[2](02-ai-agent-processing-and-extraction.md)), through signal scoring ([Page 3](03-signal-scoring-and-weighted-signals.md)) and trend aggregation ([Page 4](04-trend-aggregation-and-accumulating-signals.md)), to the recommendation ([Page 5](05-recommendation-generation.md)), the trading decision, the risk evaluation, and the broker response — every step is persisted and linked by foreign keys. The `trading_decisions` table links to `recommendations` via `recommendation_id`, the `orders` table links back to both, and the `positions` and `portfolio_snapshots` tables capture the portfolio impact over time.
For additional reference on the trading engine's configuration, queue topology, and database tables, see [docs/services.md](../services.md).
---
## Conclusion: From Raw Data to Trade Execution
This six-page series has traced the full intelligence-to-decision pipeline in Stonks Oracle, from the moment raw data enters the system to the moment an order reaches the broker.
It began with [Page 1](01-data-ingestion-and-preparation.md), where the scheduler orchestrates ingestion cycles across four data sources — Polygon news, SEC EDGAR filings, Polygon market data, and macro news APIs — and the parser normalizes raw content into structured documents ready for AI processing. [Page 2](02-ai-agent-processing-and-extraction.md) described how the Document Intelligence Extractor and Global Event Classifier agents use LLM inference to produce structured JSON intelligence, with hot-swappable model configurations and a robust JSON repair pipeline. [Page 3](03-signal-scoring-and-weighted-signals.md) explained how raw extraction output is transformed into `WeightedSignal` objects through a composite formula that balances recency, credibility, novelty, and market context across three independent signal layers. [Page 4](04-trend-aggregation-and-accumulating-signals.md) showed how the aggregation engine merges these signals across five time windows, detecting contradictions, ranking evidence, and computing trend projections — with consecutive same-direction signals accumulating to escalate the system's response from neutral through watch and hold to buy or sell. [Page 5](05-recommendation-generation.md) covered the translation of trend assessments into actionable recommendations through data quality suppression, eligibility evaluation, position sizing, thesis generation, and risk classification.
And here in Page 6, the pipeline reached its terminus: the trading engine's decision loop polling those recommendations, subjecting each to circuit breaker checks, confidence gates, deduplication, portfolio health assessments, and a multi-step position sizer — then submitting approved orders through the broker adapter to Alpaca's paper trading API, with every decision recorded in a fully auditable trail from signal to execution.
The pipeline is designed to be conservative by default and transparent throughout. Every stage applies its own safety checks — deduplication at ingestion, confidence gates at extraction, contradiction detection at aggregation, suppression at recommendation, and circuit breakers at trading. The system can be tuned through runtime configuration (risk tier parameters, suppression thresholds, signal layer toggles in `risk_configs`) without code changes or restarts. And the complete audit trail — from `documents` through `document_intelligence`, `document_impact_records`, `trend_windows`, `recommendations`, `trading_decisions`, and `orders` — means that any trade can be traced back to the specific documents, signals, and decisions that produced it.
@@ -0,0 +1 @@
@@ -0,0 +1,81 @@
# Ingestion-to-Extraction Flow
```mermaid
flowchart TD
subgraph Scheduler["Scheduler\nservices/scheduler/app.py"]
S1["schedule_cycle()"]
S2["Cadence check\nmarket_api: 300s\nnews_api: 300s\nfilings_api: 3600s\nmacro_news: 600s"]
S3["Rate limit check\ncheck_rate_limit()"]
S1 --> S2 --> S3
end
S3 -->|"rpush"| Q_ING["stonks:queue:ingestion"]
Q_ING -->|"lpop"| ING
subgraph ING["Ingestion Worker\nservices/ingestion/worker.py"]
direction TB
AD["Adapter Dispatch\nprocess_job()"]
AD --> PA["PolygonMarketAdapter\nservices/adapters/market_adapter.py"]
AD --> PB["PolygonNewsAdapter\nservices/adapters/news_adapter.py"]
AD --> PC["SECEdgarAdapter\nservices/adapters/filings_adapter.py"]
AD --> PD["MacroNewsAdapter\nservices/adapters/macro_news_adapter.py"]
AD --> PE["WebScrapeAdapter\nservices/adapters/web_scrape_adapter.py"]
end
ING -->|"Content hash check\nstonks:dedupe:*\nTTL 24h"| REDIS_DEDUPE[("Redis\nDedupe Markers")]
ING -->|"upload_raw_artifact()"| MINIO_RAW
subgraph MINIO_RAW["MinIO Raw Storage"]
B1["stonks-raw-market"]
B2["stonks-raw-news"]
B3["stonks-raw-filings"]
end
ING -->|"persist_ingestion_items()"| PG_ING
subgraph PG_ING["PostgreSQL"]
T1["documents"]
T2["ingestion_runs"]
T3["document_company_mentions"]
end
ING -->|"rpush new doc IDs"| Q_PARSE["stonks:queue:parsing"]
Q_PARSE -->|"lpop"| PARSER
subgraph PARSER["Parser Worker\nservices/parser/worker.py"]
P1["fetch_html() → parse_html()"]
P2["Quality scoring\nconfidence: high / medium / low"]
P3["Company mention detection\ndetect_company_mentions()"]
P4["Routing decision"]
P1 --> P2 --> P3 --> P4
end
PARSER -->|"upload_normalized_text()\nupload_parser_output()"| MINIO_NORM["MinIO\nstonks-normalized"]
PARSER -->|"update_document_parse_results()"| PG_ING
P4 -->|"doc_type = macro_event"| Q_MACRO["stonks:queue:macro_classification"]
P4 -->|"doc_type ≠ macro_event"| Q_EXT["stonks:queue:extraction"]
Q_EXT -->|"lpop"| EXT
Q_MACRO -->|"lpop"| EXT
subgraph EXT["Extractor Worker\nservices/extractor/main.py"]
E1["Document Intelligence\nExtractor agent\nslug: document-extractor"]
E2["Global Event Classifier\nslug: event-classifier\nservices/extractor/event_classifier.py"]
E3["persist_extraction()\nservices/extractor/worker.py"]
end
EXT -->|"persist to"| PG_EXT
subgraph PG_EXT["PostgreSQL"]
T4["document_intelligence"]
T5["document_impact_records"]
T6["global_events"]
T7["macro_impact_records"]
end
EXT -->|"rpush"| Q_AGG["stonks:queue:aggregation"]
```
@@ -0,0 +1,80 @@
# Recommendation Generation Flow
```mermaid
flowchart TD
Q_REC["stonks:queue:recommendation"] -->|"lpop"| WORKER["Recommendation Worker\nservices/recommendation/main.py"]
WORKER --> FETCH["Fetch TrendSummary\nfrom trend_windows\nfor ticker + window"]
FETCH --> SUPP
subgraph SUPP["Data Quality Suppression\nservices/recommendation/suppression.py"]
S1["extraction confidence < 0.40?"]
S2["evidence staleness > 168h?"]
S3["source diversity < 1 type?"]
S4["extraction failure rate > 50%?"]
S5["valid documents < 2?"]
S6["data quality score < 0.30?"]
S7["Macro-only signal?\nevaluate_macro_only_suppression()"]
S8["Pattern-only signal?\nevaluate_pattern_only_suppression()"]
end
SUPP -->|"Any check fails:\nsuppressed = true\nmode → informational"| ELIG
SUPP -->|"All checks pass"| ELIG
subgraph ELIG["Eligibility Evaluation\nservices/recommendation/eligibility.py"]
direction TB
G["Gate Checks"]
G1["confidence ≥ 0.35"]
G2["strength ≥ 0.10"]
G3["contradiction ≤ 0.60"]
G4["evidence ≥ 2"]
G5["direction ≠ neutral"]
G --> G1 & G2 & G3 & G4 & G5
G1 & G2 & G3 & G4 & G5 --> ACT["Action Mapping"]
ACT --> A1["BUY: bullish + strength ≥ 0.25"]
ACT --> A2["SELL: bearish + strength ≥ 0.25"]
ACT --> A3["HOLD: directional + confidence ≥ 0.50"]
ACT --> A4["WATCH: otherwise"]
A1 & A2 & A3 & A4 --> MODE["Mode Escalation"]
MODE --> M1["informational\n(default for HOLD/WATCH)"]
MODE --> M2["paper_eligible\nconfidence ≥ 0.50"]
MODE --> M3["live_eligible\nconfidence ≥ 0.70\ncontradiction ≤ 0.25\nevidence ≥ 5"]
end
ELIG --> SIZING
subgraph SIZING["Position Sizing\nservices/recommendation/eligibility.py"]
PS1["base = 1% portfolio"]
PS2["scale by confidence × strength\nup to 10% max"]
PS3["contradiction penalty\n0.5 × contradiction_score"]
PS4["evidence count penalty\n< 3 docs → ×0.5\n< 5 docs → ×0.75"]
end
SIZING --> THESIS
subgraph THESIS["Thesis Generation"]
TH1["Deterministic thesis\nassembled from trend data"]
TH2["Optional LLM rewrite\nthesis-rewriter agent\nservices/recommendation/thesis_llm.py"]
TH1 --> TH2
end
THESIS --> RISK
subgraph RISK["Risk Classification"]
RC1["low"]
RC2["moderate"]
RC3["high"]
RC4["very_high"]
end
RISK --> PERSIST
subgraph PERSIST["Persistence — PostgreSQL"]
P1["recommendations"]
P2["recommendation_evidence"]
P3["risk_evaluations"]
end
```
@@ -0,0 +1,52 @@
# Three-Layer Signal Merging
```mermaid
flowchart TD
subgraph Layer1["Layer 1 — Company Signals"]
DIR["document_impact_records\n(per-company extraction output)"]
DIR -->|"build_weighted_signals()"| WS1["WeightedSignal[]\nweight = 1.0 (full)"]
end
subgraph Layer2["Layer 2 — Macro Signals"]
MIR["macro_impact_records\n(global event interpolation)"]
MIR -->|"build_macro_weighted_signals()"| WS2["WeightedSignal[]\nimpact × MACRO_SIGNAL_WEIGHT\n(0.3)"]
TOGGLE_M{"macro_enabled\nin risk_configs?"}
TOGGLE_M -->|"true"| MIR
TOGGLE_M -->|"false"| SKIP_M["Layer skipped\ngraceful degradation"]
end
subgraph Layer3["Layer 3 — Competitive Signals"]
CSR["competitive_signal_records\n(pattern mining + propagation)"]
CSR -->|"build_pattern_weighted_signals()\nservices/aggregation/signal_propagation.py"| WS3["WeightedSignal[]\nimpact × COMPETITIVE_SIGNAL_WEIGHT\n(0.2)"]
TOGGLE_C{"competitive_enabled\nin risk_configs?"}
TOGGLE_C -->|"true"| CSR
TOGGLE_C -->|"false"| SKIP_C["Layer skipped\ngraceful degradation"]
end
WS1 --> MERGE["Concatenate all WeightedSignal lists"]
WS2 --> MERGE
WS3 --> MERGE
MERGE --> AGG
subgraph AGG["Aggregation Engine\nservices/aggregation/worker.py"]
A1["weighted_sentiment_average()"]
A2["detect_contradictions()\nservices/aggregation/contradiction.py"]
A3["derive_trend_direction()"]
A4["compute_trend_confidence()"]
A5["rank_evidence()"]
A1 --> A2 --> A3 --> A4 --> A5
end
AGG -->|"assemble_trend_summary()"| TS["TrendSummary\nservices/shared/schemas.py"]
TS -->|"persist_trend_summary()"| PG_TREND
subgraph PG_TREND["PostgreSQL"]
TW["trend_windows\n(upserted each cycle)"]
TH["trend_history\n(time-series snapshots)"]
TE["trend_evidence\n(per-document rankings)"]
end
AGG -->|"rpush"| Q_REC["stonks:queue:recommendation"]
```
@@ -0,0 +1,94 @@
# Trading Engine Decision Loop
```mermaid
flowchart TD
subgraph ENGINE["Trading Engine\nservices/trading/engine.py"]
direction TB
TASKS["5 Concurrent Async Tasks"]
T1["_decision_loop()\n60s polling interval"]
T2["_stop_loss_monitor()"]
T3["_performance_loop()"]
T4["_risk_tier_scheduler()"]
T5["_rebalance_scheduler()"]
TASKS --> T1 & T2 & T3 & T4 & T5
end
T1 --> POLL["Poll recommendations table\naction IN (buy, sell)\nmode IN (paper_eligible, live_eligible)\ngenerated_at > NOW() 2h"]
POLL --> EVAL["evaluate_recommendation()"]
EVAL --> CHK_A
subgraph PRETRADE["Pre-Trade Check Sequence\n(first failure short-circuits)"]
direction TB
CHK_A["a. Circuit Breaker active?\nservices/trading/circuit_breaker.py\nTriggers: daily_loss, single_position, volatility"]
CHK_B["b. Trading Window?\nis_within_trading_window()"]
CHK_C["c. Confidence Gate\nconfidence ≥ risk_tier.min_confidence"]
CHK_D["d. Deduplication\nRec ID in processed set?\nRedis: stonks:dedupe:trading:*"]
CHK_E["e. Declining Positions\n> 50% positions down > 2%"]
CHK_F["f. Max Open Positions\nopen_count ≥ max (default 10)"]
CHK_A -->|"pass"| CHK_B
CHK_B -->|"pass"| CHK_C
CHK_C -->|"pass"| CHK_D
CHK_D -->|"pass"| CHK_E
CHK_E -->|"pass"| CHK_F
end
CHK_A & CHK_B & CHK_C & CHK_D & CHK_E & CHK_F -->|"fail"| SKIP["TradingDecision\ndecision = skip\n+ skip_reason"]
CHK_F -->|"pass"| SIZER
subgraph SIZER["Position Sizing\nservices/trading/position_sizer.py"]
direction TB
SZ1["Base sizing\nrisk_tier.max_position_pct × 0.5\n× (confidence / min_confidence)"]
SZ2["Correlation reduction\nweighted avg corr > 0.8 → reject\n> 0.5 → proportional reduction"]
SZ3["Sector exposure\ncap at risk_tier.max_sector_pct"]
SZ4["Diversification bonus\n1.2× for new sector (< 3 sectors)"]
SZ5["Earnings proximity\n≤ 1 day → reject\n≤ 3 days → 50% reduction"]
SZ6["Absolute position cap"]
SZ7["Portfolio heat check\nmax_portfolio_heat × active_pool"]
SZ8["Share rounding\nfloor(dollar / price)"]
SZ1 --> SZ2 --> SZ3 --> SZ4 --> SZ5 --> SZ6 --> SZ7 --> SZ8
end
SIZER -->|"rejected"| SKIP
SIZER -->|"approved"| ACT["TradingDecision\ndecision = act\nshares, dollar amount"]
ACT --> PERSIST_TD["Persist to\ntrading_decisions"]
ACT --> ORDER["Build order job\n{ticker, action, side,\nquantity, order_type}"]
ORDER -->|"rpush"| Q_BROKER["stonks:queue:broker_orders"]
Q_BROKER --> BROKER["Broker Adapter\nAlpaca paper trading\nservices/adapters/broker_adapter.py"]
BROKER --> AUDIT
subgraph AUDIT["Audit Trail — PostgreSQL"]
AU1["orders"]
AU2["positions"]
AU3["portfolio_snapshots"]
end
subgraph CB_DETAIL["Circuit Breaker Detail\nservices/trading/circuit_breaker.py"]
CB1["daily_loss\nportfolio loss > 5%\ncooldown: volatility_pause_hours"]
CB2["single_position\nposition loss > 15%\ncooldown: ticker_cooldown_hours (48h)"]
CB3["volatility\n≥ 3 stop-losses in 30min\ncooldown: volatility_pause_hours (2h)"]
CB4["Redis state\nstonks:trading:circuit_breaker:*"]
end
subgraph RESERVE["Reserve Pool\nservices/trading/reserve_pool.py"]
RP1["Profit siphoning: 20%"]
RP2["High-water rebalance: 30%"]
RP3["Emergency liquidation"]
RP4["reserve_pool_ledger"]
end
subgraph RISK_TIER["Risk Tier Auto-Adjustment\nservices/trading/risk_tier_controller.py"]
RT1["Evaluate: Sharpe ratio,\ndrawdown, win rate"]
RT2["conservative → moderate → aggressive"]
RT3["risk_tier_history"]
end
```
@@ -0,0 +1,62 @@
# Trend Accumulation and Escalation
```mermaid
flowchart TD
subgraph Windows["Five Time Windows\nservices/aggregation/worker.py"]
W1["intraday (12h)"]
W2["1d (1 day)"]
W3["7d (7 days)"]
W4["30d (30 days)"]
W5["90d (90 days)"]
end
W1 & W2 & W3 & W4 & W5 --> SIGNALS
SIGNALS["Fetch signals per window\nCompany + Macro + Competitive\n→ WeightedSignal[]"]
SIGNALS --> SENT["weighted_sentiment_average()\nCompute avg sentiment across signals"]
SENT --> DIR
subgraph DIR["derive_trend_direction()"]
D1["avg_sentiment ≥ 0.15 → BULLISH"]
D2["avg_sentiment ≤ 0.15 → BEARISH"]
D3["contradiction > 0.10\nAND |avg| < 0.30 → MIXED"]
D4["otherwise → NEUTRAL"]
end
DIR --> CONF
subgraph CONF["compute_trend_confidence()"]
C1["Unique source count\ncaps at 15 → 0.8 contribution"]
C2["Avg extraction credibility"]
C3["Signal agreement ratio\ndampened by log₂(n+1)/log₂(8)\nsaturates ~7 unique sources"]
C4["Contradiction penalty\n0.4 × contradiction_score"]
C5["confidence = 0.3×count + 0.3×credibility\n+ 0.4×agreement penalty"]
end
CONF --> STRENGTH["trend_strength = |avg_sentiment|\nclamped to [0, 1]"]
STRENGTH --> ESC
subgraph ESC["Escalation Path\n(via eligibility thresholds)"]
direction TB
E1["NEUTRAL\nconfidence < 0.35\nOR strength < 0.10\nOR direction = neutral"]
E2["WATCH\nstrength < 0.25\nAND confidence < 0.50"]
E3["HOLD\nstrength < 0.25\nAND confidence ≥ 0.50"]
E4["BUY / SELL\nstrength ≥ 0.25\nAND direction = bullish/bearish"]
E1 -->|"More signals\nsame direction"| E2
E2 -->|"Confidence grows\nmore unique sources"| E3
E3 -->|"Strength exceeds 0.25\naccumulated evidence"| E4
end
ESC --> PERSIST
subgraph PERSIST["Persistence"]
P1["trend_windows\n(upserted each cycle)"]
P2["trend_history\n(time-series snapshots)"]
P3["trend_evidence\n(per-document rankings)"]
P4["trend_projections\nservices/aggregation/projection.py"]
end
```
@@ -0,0 +1,58 @@
# Weighted Signal Computation
```mermaid
flowchart TD
DOC["Document Signal Input\n(published_at, source_credibility,\nnovelty_score, extraction_confidence,\nmarket_ctx)"]
DOC --> GATE
DOC --> REC
DOC --> CRED
DOC --> NOV
DOC --> MKT
subgraph GATE["Confidence Gate"]
G1["extraction_confidence ≥ 0.2?"]
G1 -->|"Yes"| G2["gate = 1.0"]
G1 -->|"No"| G3["gate = 0.0\n(signal zeroed out)"]
end
subgraph REC["Recency Decay"]
R1["w = 2^(age_hours / half_life)"]
R2["Half-lives per window:\nintraday: 2h\n1d: 12h\n7d: 72h\n30d: 240h\n90d: 720h"]
R3["Floor: min_recency_weight = 0.01"]
R1 --- R2
R1 --- R3
end
subgraph CRED["Source Credibility"]
C1["Clamp to [0.1, 1.0]"]
C2["Apply exponent\n(default 1.0)"]
C1 --> C2
end
subgraph NOV["Novelty Bonus"]
N1["bonus = novelty_score × 0.25"]
N2["Range: [0.0, 0.25]\n(up to 25% boost)"]
N1 --- N2
end
subgraph MKT["Market Context Multiplier"]
M1["Volatility boost\nlog₁₊(excess) × 0.15\ncapped at 0.30"]
M2["Volume surge boost\nvolume_change > 50% → +0.15"]
M3["multiplier = 1.0 + boost\n(always ≥ 1.0)"]
M1 --> M3
M2 --> M3
end
GATE --> FORMULA
REC --> FORMULA
CRED --> FORMULA
NOV --> FORMULA
MKT --> FORMULA
FORMULA["combined = gate × recency × credibility\n× (1 + novelty_bonus)\n× market_context_multiplier"]
FORMULA --> SW["SignalWeight\nservices/aggregation/scoring.py"]
SW --> WS["WeightedSignal\n{ document_id, weight: SignalWeight,\nsentiment_value, impact_score }"]
```
@@ -0,0 +1,40 @@
# Intelligence Pipeline Deep Dive
This document series provides a narrative walkthrough of the full intelligence-to-decision pipeline in Stonks Oracle. Unlike the existing service reference and API documentation, these pages tell the story of how raw data enters the system, gets processed by AI agents, produces structured signals, accumulates into trend summaries, and ultimately drives autonomous trading decisions.
Each page covers one stage of the pipeline and ends with a transition to the next, so you can read the series end-to-end or jump directly to the stage you need. Diagrams are stored as standalone Mermaid files that can be rendered independently or embedded in other documents.
---
## Table of Contents
1. [Data Ingestion and Preparation](01-data-ingestion-and-preparation.md) — How raw data from Polygon.io, SEC EDGAR, and macro news APIs enters the system, gets deduplicated, stored, parsed, and routed for AI processing.
2. [AI Agent Processing and Structured Extraction](02-ai-agent-processing-and-extraction.md) — How the Document Intelligence Extractor and Global Event Classifier agents use LLM inference to produce structured JSON intelligence from documents.
3. [Signal Scoring and the WeightedSignal Abstraction](03-signal-scoring-and-weighted-signals.md) — How raw extraction output is transformed into weighted signals through confidence gating, recency decay, source credibility, novelty bonuses, and market context multipliers.
4. [Trend Aggregation and Accumulating Signals](04-trend-aggregation-and-accumulating-signals.md) — How the aggregation engine merges weighted signals across five time windows, detects contradictions, ranks evidence, and escalates trend strength as consecutive signals accumulate.
5. [Recommendation Generation](05-recommendation-generation.md) — How trend summaries pass through data quality suppression, eligibility evaluation, position sizing, thesis generation, and risk classification to produce actionable recommendations.
6. [Trading Decisions and Execution](06-trading-decisions-and-execution.md) — How the trading engine polls recommendations, runs pre-trade checks, sizes positions, enforces circuit breakers, and submits orders through the broker adapter.
---
## Diagrams
The following Mermaid diagram files can be rendered independently or referenced from the narrative pages:
- [Ingestion to Extraction Flow](diagrams/ingestion-to-extraction-flow.md) — Flowchart from Scheduler through Ingestion, Parser, to Extractor with all queues and storage.
- [Three-Layer Signal Merging](diagrams/three-layer-signal-merging.md) — Company, Macro, and Competitive signal layers converging into the Aggregation engine.
- [Weighted Signal Computation](diagrams/weighted-signal-computation.md) — Component breakdown of the composite weight formula.
- [Trend Accumulation and Escalation](diagrams/trend-accumulation-escalation.md) — How consecutive signals strengthen trends and escalate actions across time windows.
- [Recommendation Generation Flow](diagrams/recommendation-generation-flow.md) — From TrendSummary through suppression, eligibility, thesis, risk classification, to persistence.
- [Trading Engine Decision Loop](diagrams/trading-engine-decision-loop.md) — Pre-trade check sequence, position sizing, and order submission flow.
---
## Related Documentation
For reference-level detail on individual services, AI agent configuration, and infrastructure, see the existing documentation:
- [Services Reference](../services.md) — Per-service configuration, database tables, queues, and runtime behaviors.
- [AI Agents Guide](../ai-agents.md) — AI agent configuration, variants, A/B testing, and the agent management API.
- [Data Pipeline Architecture](../architecture-data-pipeline.md) — Queue topology, data store summary, and Mermaid flow diagrams for the full data pipeline.
- [LLM-to-Trade Pipeline](../llm-to-trade-pipeline.md) — End-to-end data flow from model output through signal aggregation to trade execution.
+612
View File
@@ -0,0 +1,612 @@
# Observability and Metrics Reference
This document covers the full observability stack for Stonks Oracle: Prometheus metrics, operational alerting, structured logging, dead-letter queues, and recommended monitoring queries.
## Prometheus Metrics Endpoint
The Query API exposes a `/metrics` endpoint that returns all registered Prometheus metrics in the standard text exposition format.
**Endpoint**: `GET /metrics` on the Query API service (port 8000)
**Response**: `text/plain; version=0.0.4; charset=utf-8` — standard Prometheus scrape format via `prometheus_client.generate_latest()`.
### Prometheus Scrape Configuration
Add the following job to your `prometheus.yml`:
```yaml
scrape_configs:
- job_name: "stonks-oracle"
scrape_interval: 15s
scrape_timeout: 10s
metrics_path: /metrics
static_targets:
- targets:
# Docker Compose
- "query-api:8000"
# Kubernetes
# - "query-api.stonks-oracle.svc.cluster.local:8000"
```
For Kubernetes deployments, you can also use a `ServiceMonitor` resource if the Prometheus Operator is installed:
```yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: stonks-oracle
namespace: stonks-oracle
spec:
selector:
matchLabels:
app: query-api
endpoints:
- port: http
path: /metrics
interval: 15s
```
---
## Prometheus Metrics Reference
All metrics are defined in `services/shared/metrics.py`. Metric names use the `stonks_` prefix.
### Service Info
| Metric | Type | Description |
|--------|------|-------------|
| `stonks_oracle_info` | Info | Service metadata (build version, etc.) |
### Ingestion Metrics
| Metric | Type | Labels | Description |
|--------|------|--------|-------------|
| `stonks_ingestion_jobs_total` | Counter | `source_type`, `status` | Total ingestion jobs processed |
| `stonks_ingestion_items_fetched_total` | Counter | `source_type` | Total items fetched from external sources |
| `stonks_ingestion_items_new_total` | Counter | `source_type` | New (non-duplicate) items ingested |
| `stonks_ingestion_items_deduped_total` | Counter | `source_type` | Items skipped due to deduplication |
| `stonks_ingestion_errors_total` | Counter | `source_type` | Ingestion errors by source type |
| `stonks_ingestion_adapter_duration_seconds` | Histogram | `source_type` | Adapter fetch latency (buckets: 0.1, 0.5, 1, 2, 5, 10, 30, 60s) |
### Parsing Metrics
| Metric | Type | Labels | Description |
|--------|------|--------|-------------|
| `stonks_parse_jobs_total` | Counter | `status` | Total parse jobs processed |
| `stonks_parse_quality_score` | Histogram | — | Distribution of parser quality scores (buckets: 0.11.0 in 0.1 steps) |
| `stonks_parse_low_quality_total` | Counter | — | Documents flagged as low quality by the parser |
| `stonks_parse_duration_seconds` | Histogram | — | Parse job duration (buckets: 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10s) |
### Extraction Metrics
| Metric | Type | Labels | Description |
|--------|------|--------|-------------|
| `stonks_extraction_jobs_total` | Counter | `status` | Total extraction jobs processed |
| `stonks_extraction_attempts_total` | Counter | — | Total Ollama extraction attempts (including retries) |
| `stonks_extraction_retries_total` | Counter | — | Extraction retry count |
| `stonks_extraction_duration_seconds` | Histogram | — | Extraction total duration (buckets: 1, 2, 5, 10, 20, 30, 60, 120s) |
| `stonks_extraction_confidence` | Histogram | — | Distribution of extraction confidence scores (buckets: 0.11.0) |
| `stonks_extraction_validation_errors_total` | Counter | — | Total validation errors across extractions |
| `stonks_extraction_tokens_total` | Counter | `direction` | Estimated token usage (labels: `input`, `output`) |
### Aggregation Metrics
| Metric | Type | Labels | Description |
|--------|------|--------|-------------|
| `stonks_aggregation_windows_total` | Counter | `window` | Trend windows computed |
| `stonks_aggregation_signals_total` | Counter | `window` | Signals processed during aggregation |
| `stonks_aggregation_contradiction_score` | Histogram | — | Distribution of contradiction scores in trend windows (buckets: 0.01.0) |
| `stonks_aggregation_duration_seconds` | Histogram | `window` | Aggregation job duration (buckets: 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10s) |
### Recommendation Metrics
| Metric | Type | Labels | Description |
|--------|------|--------|-------------|
| `stonks_recommendations_total` | Counter | `action`, `mode` | Recommendations generated |
| `stonks_recommendations_suppressed_total` | Counter | — | Recommendations suppressed due to low data quality |
| `stonks_recommendation_confidence` | Histogram | — | Distribution of recommendation confidence scores (buckets: 0.11.0) |
### Lake Publication Metrics
| Metric | Type | Labels | Description |
|--------|------|--------|-------------|
| `stonks_lake_facts_published_total` | Counter | `table_name` | Analytical facts published to the lakehouse |
| `stonks_lake_publish_duration_seconds` | Histogram | `table_name` | Lake publication write latency (buckets: 0.01, 0.05, 0.1, 0.25, 0.5, 1, 2, 5s) |
| `stonks_lake_publish_errors_total` | Counter | `table_name` | Lake publication errors |
| `stonks_lake_publish_bytes_total` | Counter | `table_name` | Total bytes written to the lakehouse |
### Trading and Broker Metrics
| Metric | Type | Labels | Description |
|--------|------|--------|-------------|
| `stonks_orders_submitted_total` | Counter | `side`, `order_type`, `mode` | Orders submitted to broker |
| `stonks_orders_rejected_total` | Counter | `reason_category` | Orders rejected before broker submission |
| `stonks_orders_filled_total` | Counter | `side` | Orders filled by broker |
| `stonks_orders_duplicates_prevented_total` | Counter | `detected_via` | Duplicate orders prevented by idempotency checks |
| `stonks_risk_evaluations_total` | Counter | `result` | Risk evaluations performed |
| `stonks_risk_check_failures_total` | Counter | `check_name` | Individual risk check failures |
| `stonks_positions_synced_total` | Counter | — | Position sync operations completed |
### Alerting Metrics
| Metric | Type | Labels | Description |
|--------|------|--------|-------------|
| `stonks_alerts_fired_total` | Counter | `rule`, `severity` | Total alerts fired by rule |
| `stonks_alerts_resolved_total` | Counter | `rule` | Total alerts resolved by rule |
| `stonks_alert_check_duration_seconds` | Histogram | — | Duration of alert evaluation cycle (buckets: 0.015s) |
| `stonks_alert_active` | Gauge | `rule` | Whether an alert rule is currently firing (1) or resolved (0) |
### Dead-Letter Queue Metrics
| Metric | Type | Labels | Description |
|--------|------|--------|-------------|
| `stonks_dlq_items_total` | Counter | `queue` | Jobs sent to dead-letter queues |
| `stonks_dlq_replayed_total` | Counter | `queue` | Jobs replayed from dead-letter queues |
| `stonks_dlq_depth` | Gauge | `queue` | Current dead-letter queue depth |
### Active Jobs Gauge
| Metric | Type | Labels | Description |
|--------|------|--------|-------------|
| `stonks_active_jobs` | Gauge | `stage` | Currently processing jobs by pipeline stage |
---
## Alerting Module
The alerting module (`services/shared/alerting.py`) evaluates four operational alert rules against PostgreSQL state on a configurable interval. When a threshold is breached, the module emits structured log events and increments Prometheus counters. When a previously firing alert clears, it logs a resolution event.
### Alert Rules
#### 1. `source_failures` — Sustained Source Retrieval Failures
Detects sources where the last N ingestion runs all failed within the lookback window.
| Parameter | ConfigMap Variable | Default | Description |
|-----------|--------------------|---------|-------------|
| Consecutive failure threshold | `ALERT_SOURCE_FAILURE_THRESHOLD` | `3` | Number of consecutive failures before alert fires |
| Lookback window | `ALERT_SOURCE_FAILURE_WINDOW_HOURS` | `6` hours | How far back to check ingestion_runs |
**Severity**: `warning`
**Query**: Checks `ingestion_runs` for sources where the most recent N runs (within the window) all have `status = 'failed'`.
**Details emitted**: `source_id`, `source_type`, `source_name`, `ticker`, `consecutive_failures`
#### 2. `schema_failure_spike` — Extraction Validation Failure Rate
Detects when the extraction schema validation failure rate exceeds a threshold.
| Parameter | ConfigMap Variable | Default | Description |
|-----------|--------------------|---------|-------------|
| Failure rate threshold | `ALERT_SCHEMA_FAILURE_RATE_THRESHOLD` | `0.3` (30%) | Failure rate that triggers the alert |
| Lookback window | `ALERT_SCHEMA_FAILURE_WINDOW_HOURS` | `1` hour | Window for computing failure rate |
**Severity**: `warning` if rate ≥ 30%, `critical` if rate ≥ 50%
**Query**: Computes `failed / total` from `model_performance_metrics` within the window.
**Details emitted**: `total_extractions`, `failed_extractions`, `failure_rate`, `threshold`, `window_hours`
#### 3. `analytical_lag` — Lake Publication Lag
Detects when lake publication has not completed within the threshold for any table.
| Parameter | ConfigMap Variable | Default | Description |
|-----------|--------------------|---------|-------------|
| Lag threshold | `ALERT_LAKE_LAG_THRESHOLD_MINUTES` | `60` minutes | Maximum acceptable time since last successful publish |
**Severity**: `warning`
**Query**: Checks `audit_events` for the most recent successful `lake_publish` event per table, alerts if any are older than the threshold.
**Details emitted**: `table_name`, `last_publish`, `lag_minutes`, `threshold_minutes`
#### 4. `broker_issues` — Consecutive Broker Errors
Detects consecutive broker submission errors (rejections, timeouts, connection failures).
| Parameter | ConfigMap Variable | Default | Description |
|-----------|--------------------|---------|-------------|
| Error threshold | `ALERT_BROKER_ERROR_THRESHOLD` | `3` | Consecutive broker errors before alert fires |
| Lookback window | `ALERT_BROKER_ERROR_WINDOW_HOURS` | `1` hour | Window for checking order_events |
**Severity**: `critical`
**Query**: Counts recent `order_events` with `event_type IN ('broker_error', 'broker_timeout', 'connection_failed')`.
**Details emitted**: `error_count`, `threshold`, `window_hours`
### Evaluation Cycle
The alerting module runs on a configurable interval (default: every 120 seconds, controlled by `ALERT_CHECK_INTERVAL_SECONDS`). Each cycle:
1. Runs all four alert rules against PostgreSQL
2. Compares results to the current `AlertState` to detect new firings and resolutions
3. For new firings: increments `stonks_alerts_fired_total`, sets `stonks_alert_active` gauge to 1, logs a `WARNING`
4. For resolutions: increments `stonks_alerts_resolved_total`, sets `stonks_alert_active` gauge to 0, logs an `INFO`
5. Records the evaluation duration in `stonks_alert_check_duration_seconds`
Each rule check is wrapped in a try/except so a failure in one rule does not block the others.
### ConfigMap Variables Summary
| Variable | Default | Description |
|----------|---------|-------------|
| `ALERT_SOURCE_FAILURE_THRESHOLD` | `3` | Consecutive source failures before alert |
| `ALERT_SOURCE_FAILURE_WINDOW_HOURS` | `6` | Source failure lookback window (hours) |
| `ALERT_SCHEMA_FAILURE_RATE_THRESHOLD` | `0.3` | Extraction failure rate threshold (0.01.0) |
| `ALERT_SCHEMA_FAILURE_WINDOW_HOURS` | `1` | Schema failure lookback window (hours) |
| `ALERT_LAKE_LAG_THRESHOLD_MINUTES` | `60` | Max minutes since last lake publish |
| `ALERT_BROKER_ERROR_THRESHOLD` | `3` | Consecutive broker errors before alert |
| `ALERT_BROKER_ERROR_WINDOW_HOURS` | `1` | Broker error lookback window (hours) |
| `ALERT_CHECK_INTERVAL_SECONDS` | `120` | Seconds between alert evaluation cycles |
---
## Structured Logging
All services use structured JSON logging configured via `services/shared/logging.py`. Call `setup_logging(service_name)` once at service startup.
### JSON Log Format
Each log line is a single JSON object with the following fields:
```json
{
"timestamp": "2025-01-15T12:34:56.789012+00:00",
"level": "INFO",
"logger": "ingestion_worker",
"message": "Processed job for AAPL",
"service": "ingestion_worker",
"trace_id": "a1b2c3d4e5f67890",
"span_id": "1a2b3c4d"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `timestamp` | string (ISO 8601) | UTC timestamp of the log event |
| `level` | string | Log level: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL` |
| `logger` | string | Python logger name |
| `message` | string | Human-readable log message |
| `service` | string | Service name set at startup (e.g., `ingestion_worker`, `scheduler`) |
| `trace_id` | string | 16-character hex trace ID for distributed tracing |
| `span_id` | string | 8-character hex span ID for the current operation |
### Additional Context Fields
When present, these fields are merged into the JSON output:
| Field | Source | Description |
|-------|--------|-------------|
| `span_operation` | `Span` context manager | Name of the traced operation |
| `span_status` | `Span` context manager | `ok` or `error` |
| `span_duration_ms` | `Span` context manager | Duration of the span in milliseconds |
| `span_parent_id` | `Span` context manager | Parent span ID for nested spans |
| `span_attributes` | `Span` context manager | Arbitrary key-value attributes set on the span |
| `ticker` | Manual `extra={}` | Company ticker symbol |
| `document_id` | Manual `extra={}` | Document UUID |
| `source_type` | Manual `extra={}` | Source type (e.g., `polygon`, `news_api`) |
| `job_id` | Manual `extra={}` | Job identifier |
| `duration_ms` | Manual `extra={}` | Operation duration |
| `error` | Manual `extra={}` | Error description |
| `count` | Manual `extra={}` | Item count |
| `exception` | Automatic | Formatted exception traceback (when `exc_info` is set) |
### Trace Context Propagation
Trace context flows through the pipeline via job payloads:
1. **Inject**: Before enqueuing a job to Redis, call `inject_trace_context(payload)` to add `_trace_id` to the payload dict.
2. **Extract**: At the start of job processing, call `extract_trace_context(payload)` to restore the trace context (or generate a new one if absent).
3. **Span**: Use the `Span` context manager to create child spans within a service:
```python
from services.shared.logging import Span
with Span("process_document", ticker="AAPL") as span:
# ... do work ...
span.set_attribute("doc_count", 5)
```
This produces a structured log entry on span exit with duration, status, and attributes.
### Log Querying
To trace a request through the pipeline, filter by `trace_id`:
```bash
# Kubernetes — find all logs for a specific trace
kubectl logs -n stonks-oracle -l app.kubernetes.io/part-of=stonks-oracle --all-containers \
| jq -r 'select(.trace_id == "a1b2c3d4e5f67890")'
# Docker Compose — search across all services
docker compose logs --no-color | grep '"trace_id":"a1b2c3d4e5f67890"'
```
To find errors in a specific service:
```bash
# Kubernetes
kubectl logs -n stonks-oracle deployment/extractor --tail=500 \
| jq 'select(.level == "ERROR")'
# Docker Compose
docker compose logs extractor --no-color --tail=500 \
| jq 'select(.level == "ERROR")'
```
To find slow extraction spans:
```bash
kubectl logs -n stonks-oracle deployment/extractor --tail=1000 \
| jq 'select(.span_operation == "extract_document" and .span_duration_ms > 30000)'
```
---
## Dead-Letter Queue System
When a worker fails to process a job after exhausting retries (default: 3 attempts), the job is pushed to a per-queue dead-letter list in Redis. The DLQ system is implemented in `services/shared/dead_letter.py`.
### Queue Names
Dead-letter queues follow the naming pattern `stonks:dlq:<queue_name>`:
| DLQ Key | Source Queue | Description |
|---------|-------------|-------------|
| `stonks:dlq:ingestion` | `stonks:queue:ingestion` | Failed ingestion jobs (adapter errors, API failures) |
| `stonks:dlq:parsing` | `stonks:queue:parsing` | Failed parse jobs |
| `stonks:dlq:extraction` | `stonks:queue:extraction` | Failed extraction jobs (LLM errors, validation failures) |
| `stonks:dlq:aggregation` | `stonks:queue:aggregation` | Failed aggregation jobs |
| `stonks:dlq:recommendation` | `stonks:queue:recommendation` | Failed recommendation jobs |
| `stonks:dlq:broker_orders` | `stonks:queue:broker_orders` | Failed broker order submissions |
When `DEPLOY_STAGE` is set, the prefix becomes `stonks:<stage>:dlq:<queue_name>`.
### DLQ Entry Format
Each DLQ entry wraps the original job payload with failure metadata:
```json
{
"original_payload": {
"source_id": "...",
"source_type": "polygon",
"ticker": "AAPL",
"company_id": "...",
"config": {}
},
"queue": "ingestion",
"error": "ConnectionError: API timeout after 30s",
"attempt": 3,
"worker": "ingestion_worker",
"dead_lettered_at": "2025-01-15T12:34:56.789012+00:00"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `original_payload` | object | The original job payload as it was enqueued |
| `queue` | string | Source queue name |
| `error` | string | Error message from the final failed attempt |
| `attempt` | integer | Number of attempts made before dead-lettering |
| `worker` | string | Worker identifier that dead-lettered the job |
| `dead_lettered_at` | string (ISO 8601) | UTC timestamp when the job was dead-lettered |
### Routing
Jobs are routed to the DLQ by calling `send_to_dlq()` from worker code after retry exhaustion:
```python
from services.shared.dead_letter import send_to_dlq
await send_to_dlq(
rds=redis_client,
queue_name="ingestion",
original_payload=job,
error=str(exception),
attempt=3,
worker="ingestion_worker",
)
```
The default maximum attempts before dead-lettering is `DEFAULT_MAX_ATTEMPTS = 3`.
### Replay Tooling
The `services/shared/dead_letter.py` module provides functions for inspecting and replaying DLQ items:
| Function | Description |
|----------|-------------|
| `peek_dlq(rds, queue_name, start=0, count=10)` | Inspect DLQ entries without removing them |
| `replay_one(rds, queue_name)` | Pop the oldest DLQ entry and re-enqueue its original payload to the source queue |
| `replay_all(rds, queue_name)` | Replay every item in the DLQ back to the source queue. Returns the count replayed |
| `dlq_length(rds, queue_name)` | Return the number of items in the DLQ |
| `dlq_summary(rds, queue_names)` | Return a mapping of queue_name → DLQ depth for multiple queues |
| `purge_dlq(rds, queue_name)` | Delete all items from the DLQ. Returns count removed |
### Monitoring DLQ Depth
Use the `scripts/check_queues.py` script to inspect queue and DLQ depths from the command line:
```bash
# Docker Compose
REDIS_HOST=localhost REDIS_PORT=6379 REDIS_PASSWORD="" \
python scripts/check_queues.py
# Kubernetes
kubectl exec -n stonks-oracle deployment/query-api -- \
python scripts/check_queues.py
```
The Query API also exposes DLQ depths in the `/api/ops/pipeline/stream` SSE endpoint and the DevOps metrics endpoints, reporting `dlq:<queue_name>` keys alongside regular queue depths.
The `stonks_dlq_depth` Prometheus gauge tracks DLQ depth per queue for dashboard alerting.
---
## Recommended Prometheus/Grafana Queries
### Ingestion Throughput
```promql
# Ingestion jobs per minute by source type and status
sum(rate(stonks_ingestion_jobs_total[5m])) by (source_type, status) * 60
# New items ingested per minute
sum(rate(stonks_ingestion_items_new_total[5m])) * 60
# Deduplication ratio (higher = more duplicates being filtered)
sum(rate(stonks_ingestion_items_deduped_total[5m]))
/ sum(rate(stonks_ingestion_items_fetched_total[5m]))
# Adapter latency p95 by source type
histogram_quantile(0.95, sum(rate(stonks_ingestion_adapter_duration_seconds_bucket[5m])) by (le, source_type))
# Ingestion error rate
sum(rate(stonks_ingestion_errors_total[5m])) by (source_type)
```
### Extraction Latency and Quality
```promql
# Extraction duration p50 and p95
histogram_quantile(0.5, sum(rate(stonks_extraction_duration_seconds_bucket[5m])) by (le))
histogram_quantile(0.95, sum(rate(stonks_extraction_duration_seconds_bucket[5m])) by (le))
# Extraction success rate
sum(rate(stonks_extraction_jobs_total{status="success"}[5m]))
/ sum(rate(stonks_extraction_jobs_total[5m]))
# Average extraction confidence
histogram_quantile(0.5, sum(rate(stonks_extraction_confidence_bucket[5m])) by (le))
# Validation error rate
sum(rate(stonks_extraction_validation_errors_total[5m]))
# Token usage rate (input vs output)
sum(rate(stonks_extraction_tokens_total[5m])) by (direction)
```
### Aggregation Volume
```promql
# Trend windows computed per minute by window size
sum(rate(stonks_aggregation_windows_total[5m])) by (window) * 60
# Signals processed per minute
sum(rate(stonks_aggregation_signals_total[5m])) by (window) * 60
# Average contradiction score (higher = more conflicting signals)
histogram_quantile(0.5, sum(rate(stonks_aggregation_contradiction_score_bucket[5m])) by (le))
# Aggregation duration p95
histogram_quantile(0.95, sum(rate(stonks_aggregation_duration_seconds_bucket[5m])) by (le, window))
```
### Recommendation Generation
```promql
# Recommendations generated per minute by action
sum(rate(stonks_recommendations_total[5m])) by (action, mode) * 60
# Suppression rate
sum(rate(stonks_recommendations_suppressed_total[5m]))
/ sum(rate(stonks_recommendations_total[5m]))
# Recommendation confidence distribution
histogram_quantile(0.5, sum(rate(stonks_recommendation_confidence_bucket[5m])) by (le))
```
### Trading Engine Activity
```promql
# Orders submitted per minute by side
sum(rate(stonks_orders_submitted_total[5m])) by (side, mode) * 60
# Order rejection rate by reason
sum(rate(stonks_orders_rejected_total[5m])) by (reason_category)
# Fill rate
sum(rate(stonks_orders_filled_total[5m]))
/ sum(rate(stonks_orders_submitted_total[5m]))
# Duplicate orders prevented
sum(rate(stonks_orders_duplicates_prevented_total[5m])) by (detected_via)
# Risk evaluation outcomes
sum(rate(stonks_risk_evaluations_total[5m])) by (result)
# Risk check failure breakdown
sum(rate(stonks_risk_check_failures_total[5m])) by (check_name)
```
### Lake Publication
```promql
# Facts published per minute by table
sum(rate(stonks_lake_facts_published_total[5m])) by (table_name) * 60
# Write latency p95 by table
histogram_quantile(0.95, sum(rate(stonks_lake_publish_duration_seconds_bucket[5m])) by (le, table_name))
# Publication error rate
sum(rate(stonks_lake_publish_errors_total[5m])) by (table_name)
# Bytes written per minute
sum(rate(stonks_lake_publish_bytes_total[5m])) by (table_name) * 60
```
### Alerting Health
```promql
# Currently active alerts by rule
stonks_alert_active
# Alert firing rate
sum(rate(stonks_alerts_fired_total[1h])) by (rule, severity)
# Alert evaluation duration
histogram_quantile(0.95, sum(rate(stonks_alert_check_duration_seconds_bucket[5m])) by (le))
```
### Dead-Letter Queue Health
```promql
# Current DLQ depth by queue
stonks_dlq_depth
# DLQ inflow rate (jobs dead-lettered per minute)
sum(rate(stonks_dlq_items_total[5m])) by (queue) * 60
# DLQ replay rate
sum(rate(stonks_dlq_replayed_total[5m])) by (queue) * 60
```
### Pipeline Overview (Active Jobs)
```promql
# Currently active jobs by pipeline stage
stonks_active_jobs
# Parse quality score distribution
histogram_quantile(0.5, sum(rate(stonks_parse_quality_score_bucket[5m])) by (le))
# Low quality document rate
sum(rate(stonks_parse_low_quality_total[5m]))
/ sum(rate(stonks_parse_jobs_total[5m]))
```
### Recommended Grafana Alert Rules
| Alert | Expression | For | Severity |
|-------|-----------|-----|----------|
| High DLQ depth | `stonks_dlq_depth > 10` | 5m | warning |
| Ingestion error spike | `sum(rate(stonks_ingestion_errors_total[5m])) > 0.5` | 5m | warning |
| Extraction latency high | `histogram_quantile(0.95, sum(rate(stonks_extraction_duration_seconds_bucket[5m])) by (le)) > 60` | 10m | warning |
| Lake publication stale | `stonks_alert_active{rule="analytical_lag"} == 1` | 5m | warning |
| Broker errors active | `stonks_alert_active{rule="broker_issues"} == 1` | 1m | critical |
| Zero ingestion throughput | `sum(rate(stonks_ingestion_jobs_total[15m])) == 0` | 15m | critical |
@@ -0,0 +1,130 @@
# Page 1 — Data Ingestion and Preparation
Every signal that the platform eventually acts on begins its life as raw data pulled from an external source. Before any AI agent can extract structured intelligence, before any trend can accumulate, and before any decision can be executed, the platform must first discover new content, fetch it reliably, eliminate duplicates, store the raw artifacts for audit, and normalize the text into a form suitable for downstream processing. This page traces that journey from external API to parser output, covering the Scheduler, Ingestion Worker, deduplication layer, raw storage, and Parser in detail.
For a visual overview of the full flow described here, see the [Ingestion to Extraction Flow diagram](diagrams/ingestion-to-extraction-flow.md).
---
## Four Categories of Input Data
The platform tracks 50 entities across 10 sectors, and it draws intelligence from four distinct categories of external data. Each category has its own adapter, its own API conventions, and its own scheduling cadence, but all of them feed into the same ingestion pipeline.
The first category is **entity news**, sourced from the external data provider's news endpoint (`/v2/reference/news`). The `ExternalNewsAdapter` in `services/adapters/news_adapter.py` fetches articles linked to a specific entity identifier, returning structured results that include title, publisher, article URL, description, keywords, and publication timestamp. Each request can return up to 1,000 articles, though the default limit is 20 per fetch. The adapter tracks the most recent `published_utc` value and uses it on subsequent fetches to avoid re-retrieving articles the system has already seen.
The second category is **regulatory filings**, sourced from the public records API full-text search system (regulatory filings source). The `RegulatoryFilingsAdapter` in `services/adapters/filings_adapter.py` queries the `/LATEST/search-index` endpoint for regulatory filing types and other form types associated with an entity's identifier or CIK number. Unlike the external data provider endpoints, the public records API requires no key — only a descriptive `User-Agent` header per the API's fair-access policy. The adapter deduplicates results by accession number (`adsh`), filters out non-primary documents like XML fragments and graphics, and constructs the public records API filing index URL for each hit so downstream services can fetch the full document.
The third category is **data feeds**, also sourced from the external data provider. The `ExternalDataAdapter` in `services/adapters/market_adapter.py` supports multiple endpoints: previous-day aggregate bars (`/v2/aggs/ticker/{ticker}/prev`), range bars for custom date windows, intraday hourly bars, grouped daily bars that return data for all entities in a single call (`/v2/aggs/grouped/locale/us/market/stocks/{date}`), and entity detail lookups. Data feeds follow a different path than textual content — they do not pass through the Parser or Extractor, since the structured numeric data is already in a usable form.
The fourth category is **macro and geopolitical news**, fetched by the `MacroNewsAdapter` in `services/adapters/macro_news_adapter.py`. Unlike the other three categories, macro news is not entity-specific. These sources have `source_type='macro_news'` in the `sources` database table and may have a `NULL` `company_id`. The adapter fetches from a configurable HTTP endpoint (typically the external data provider's news API filtered for broad topics) and returns articles that describe global events — policy shifts, central bank decisions, geopolitical conflicts — rather than entity-specific developments. Macro news articles are eventually classified by the Global Event Classifier agent and routed through a separate queue, as described in [Page 2](02-ai-agent-processing-and-extraction.md).
All four adapter classes inherit from `BaseAdapter` defined in `services/adapters/base.py` and return an `AdapterResult` dataclass containing the raw payload bytes, a SHA-256 content hash, a list of parsed item dicts, HTTP metadata (status code, response time), and an error field that is `None` on success. This uniform interface allows the Ingestion Worker to handle all source types through a single dispatch mechanism.
---
## The Scheduler: Orchestrating Ingestion Cycles
The Scheduler (`services/scheduler/app.py`) is the heartbeat of the ingestion pipeline. It runs a continuous loop that ticks every 15 seconds (`SCHEDULER_TICK = 15`), and on each tick it evaluates which sources are due for their next fetch. The Scheduler does not fetch data itself — it enqueues jobs onto the `app:queue:ingestion` Redis list for the Ingestion Worker to process.
Each source type has a default polling cadence defined in the `DEFAULT_CADENCES` dictionary:
| Source Type | Default Cadence |
|------------------|-----------------|
| `market_api` | 300 seconds |
| `news_api` | 300 seconds |
| `filings_api` | 3,600 seconds |
| `macro_news` | 600 seconds |
| `web_scrape` | 1,800 seconds |
| `execution_api` | 30 seconds |
Individual sources can override their cadence via the `polling_interval_seconds` field in their `config` JSONB column in the `sources` table. The `get_cadence_for_source()` function checks for this override first, falling back to the default if none is set, and enforces a minimum interval of 10 seconds.
The Scheduler determines whether a source is due by calling `is_source_due()`, which considers several conditions. If a source has never run before (no entry in the `ingestion_runs` table), it is immediately due. If the last run failed, the Scheduler respects an exponential backoff computed by `compute_backoff()`: the delay starts at 60 seconds (`DEFAULT_BACKOFF_BASE`) and doubles with each retry up to a maximum of 3,600 seconds (`MAX_BACKOFF`). If a source has failed 10 consecutive times (`MAX_RETRY_COUNT`), the Scheduler stops scheduling it entirely until an operator manually resets the retry state. If the last run is still marked as `running`, the source is skipped to prevent double-scheduling. Otherwise, the Scheduler checks whether enough time has elapsed since the last completed run based on the source's cadence.
Rate limiting adds another layer of protection. The `check_rate_limit()` function enforces two constraints. First, each source type has a per-type limit defined in `DEFAULT_RATE_LIMITS` — for example, `market_api` and `news_api` are each capped at 20 requests per minute, while `filings_api` and `macro_news` are capped at 10. Second, because `market_api` and `news_api` both use the same external data provider API key, a global provider rate limit of 45 requests per minute (`PROVIDER_GLOBAL_RATE_LIMIT`) is enforced across both types combined. Rate limit state is tracked in Redis using keys of the form `app:ratelimit:{source_type}:{window}`, where the window is a minute-granularity timestamp. If a source type exceeds its limit, the Scheduler logs a warning and skips that source for the current tick.
The Scheduler handles three categories of sources in each cycle. First, it fetches all active entity-specific sources (excluding `macro_news`) by joining the `sources` and `companies` tables. Second, it fetches active macro news sources separately, since these may not have a `company_id`. Third, it fetches global data sources — those with `source_type='market_api'` and `company_id IS NULL` — which represent endpoints like the grouped daily bars that return data for all entities in a single API call. For intraday bar sources, the Scheduler expands a single global source into per-entity jobs for every active entity.
Each enqueued job payload includes the `source_id`, `company_id`, `ticker`, `legal_name`, `source_type`, `source_name`, `config`, `credibility_score`, a list of company `aliases` (fetched from the `company_aliases` table), and a `scheduled_at` timestamp. The job is pushed onto `app:queue:ingestion` via Redis `RPUSH`.
Beyond scheduling, the Scheduler also performs periodic maintenance. Every ~20 cycles (~5 minutes), it runs `recover_stale_documents()` to re-enqueue documents that have been stuck in `parsed` status for longer than 240 minutes — a safety net for cases where Redis loses queue entries due to pod restarts or OOM events. Every ~40 cycles (~10 minutes), it runs `retry_failed_extractions()` to give documents in `extraction_failed` status another chance, resetting them to `parsed` and deleting the failed `document_intelligence` row so the Extractor treats them as fresh. Every ~100 cycles (~25 minutes), it runs `cleanup_all_tables()` to enforce retention policies across tables like `competitive_signal_records` (30 days), `ingestion_runs` (14 days), and `execution_decisions` (90 days).
For more detail on the Scheduler's configuration and operational behavior, see the [Services Reference](../services.md).
---
## The Ingestion Worker: Adapter Dispatch and Persistence
The Ingestion Worker (`services/ingestion/worker.py`) is a long-running process that continuously pops jobs from the `app:queue:ingestion` Redis list and processes them. On startup, it initializes one instance of each adapter class and stores them in a dispatch dictionary keyed by `source_type`:
```
adapters = {
"market_api": ExternalDataAdapter(...),
"news_api": ExternalNewsAdapter(...),
"filings_api": RegulatoryFilingsAdapter(),
"web_scrape": WebScrapeAdapter(),
"execution_api": ExecutionAdapter(...),
"macro_news": MacroNewsAdapter(...),
}
```
When a job arrives, the `process_job()` function looks up the appropriate adapter by `source_type` and calls its `fetch()` method with the ticker and source config. Before fetching, it records a new row in the `ingestion_runs` table with status `running`. If the adapter returns an error, the worker calls `record_retrieval_failure()` to update the run status and increment the source's retry counter with exponential backoff timing.
On a successful fetch, the worker performs several steps in sequence. First, it uploads the raw payload to MinIO via `upload_raw_artifact()` in `services/shared/storage.py`. The target bucket is determined by the source type through the `SOURCE_BUCKET_MAP`: `market_api` payloads go to `app-raw-data`, `news_api` and `macro_news` payloads go to `app-raw-content`, and `filings_api` payloads go to `app-raw-filings`. Objects are stored under a path that encodes the source type, entity identifier, date hierarchy, and document ID — for example, `news_api/Entity-A/2025/01/15/{run_id}/raw.json`.
---
## Content Deduplication via Redis
After storing the raw artifact, the Ingestion Worker checks for duplicate content. Deduplication operates at two levels.
At the payload level, the worker checks the overall `content_hash` (a SHA-256 digest of the raw API response) against Redis. The key pattern is `app:dedupe:{content_hash}` with a 24-hour TTL (86,400 seconds). If the hash is already present, the entire payload is skipped — the `ingestion_runs` row is marked as completed with `items_new=0`, and no downstream jobs are enqueued. If the hash is new, the worker sets the marker in Redis so future fetches of identical content are caught.
At the individual item level, for source types other than `market_api` and `execution_api`, the worker calls `dedupe_items()` from `services/shared/dedupe.py`. This function checks each item against a layered deduplication strategy. The fast path checks Redis for both content-hash markers (`app:dedupe:{hash}`) and canonical-URL markers (`app:dedupe:url:{url_hash}`), both with 24-hour TTLs. If the Redis check misses, the function falls back to PostgreSQL, querying the `documents` table by `content_hash` or `canonical_url` for durable cross-source matching. When a duplicate is found through the PostgreSQL fallback, the function warms the Redis cache so subsequent checks are fast.
Items identified as duplicates are not discarded entirely. If the duplicate document was originally ingested for a different entity, the worker creates a cross-source mention link in the `document_company_mentions` table via `persist_document_company_mention()`. This ensures that a news article mentioning both Entity-A and Entity-F is linked to both entities even if it was first ingested through Entity-A's news source.
New (non-duplicate) items are persisted to PostgreSQL through `persist_ingestion_items()` in `services/shared/metadata.py`, which inserts rows into the `documents` table and records entity mentions in `document_company_mentions`. Each new document ID is then pushed onto `app:queue:parsing` for the Parser to process. After persistence, the worker calls `mark_as_seen()` to set Redis dedupe markers for both the content hash and canonical URL of each new item, ensuring that the next fetch cycle's deduplication checks are fast.
On successful completion, the worker updates the `ingestion_runs` row with the final counts (`items_fetched`, `items_new`) and calls `reset_source_retry_state()` to clear any accumulated backoff from previous failures. For news-type sources (`news_api` and `macro_news`), the worker also updates the source's `config` JSONB column with the latest `published_utc` value, so the next fetch only retrieves newer articles.
---
## The Parser: Normalization, Quality Scoring, and Routing
Documents that pass through ingestion arrive on the `app:queue:parsing` Redis list as JSON payloads containing a `document_id`, `ticker`, and `source_type`. The Parser Worker (`services/parser/worker.py`) pops these jobs and transforms raw HTML or text into normalized, quality-scored documents ready for AI extraction.
The parsing pipeline begins with HTML fetching. If the document has a URL (looked up from the `documents` table if not present in the job payload), the worker calls `fetch_html()` to retrieve the page content. Public records API URLs receive a specialized `User-Agent` header to comply with the API's fair-access policy. The raw HTML is then passed to `parse_html()` in `services/parser/html_parser.py`, which runs a multi-stage extraction pipeline.
The HTML parser first strips non-content tags — `script`, `style`, `nav`, `footer`, `header`, `aside`, `iframe`, and others — and removes boilerplate containers identified by CSS class or ID patterns (sidebars, ad slots, newsletter signups, social share bars, and similar UI elements). It then searches for the article body using a priority list of semantic selectors (`article`, `[role='main']`, `.article-body`, `.post-content`, and others). If no semantic match is found, it falls back to text-density scoring across candidate `div`, `section`, and `td` elements, selecting the block with the highest composite score based on text density, link density, paragraph count, and word count. The extracted text undergoes further cleaning: regex-based removal of residual boilerplate phrases (copyright notices, "subscribe to our newsletter" prompts, "share this article" fragments), removal of short orphan lines that are likely UI fragments, detection and collapse of repeated template blocks, and whitespace normalization.
Metadata extraction pulls the document title (from `og:title` or `<title>`), author, publisher (from `og:site_name` or hostname), publication date (from `article:published_time` or JSON-LD `datePublished`), canonical URL, language, description, and keywords from the HTML head elements.
If the parsed body text is shorter than 500 characters, the worker attempts to enrich it by reading the raw API payload from MinIO and extracting the data provider's article description, keywords, and author fields for the matching article. This enrichment step ensures that even articles with minimal scrapeable HTML still have enough textual content for meaningful AI extraction.
Quality scoring is performed by `score_parse_quality()` in `services/parser/html_parser.py`, which evaluates six weighted signals to produce a composite score between 0 and 0.95:
| Signal | Weight | What It Measures |
|--------------------|--------|-----------------------------------------------------------------|
| `word_count` | 0.30 | Length of extracted text (thresholds at 20, 50, 150, 300 words) |
| `body_found` | 0.20 | Whether a semantic article body element was located |
| `diversity` | 0.15 | Vocabulary richness (unique words / total words) |
| `sentence` | 0.15 | Presence of proper sentence structure (terminal punctuation) |
| `paragraph` | 0.10 | Multi-paragraph structure (blocks separated by blank lines) |
| `metadata` | 0.10 | Presence of title, author, publisher, and publication date |
The composite score maps to a confidence label: scores below 0.35 are labeled `low`, scores between 0.35 and 0.65 are `medium`, and scores 0.65 and above are `high`. Documents with `low` confidence are marked with status `low_quality` in the `documents` table and are not enqueued for extraction — they are effectively filtered out of the pipeline at this stage.
Entity mention detection runs next. The worker fetches all known aliases from the `company_aliases` table (plus entity identifiers and legal names from the `companies` table) and calls `detect_company_mentions()` in `services/parser/html_parser.py`. The matching strategy varies by alias length: one-to-two character aliases use case-sensitive word-boundary matching to avoid false positives (the letter "A" should not match every occurrence of the word "a"), three-to-four character aliases use case-insensitive word-boundary matching (standard identifier format), and aliases of five or more characters use case-insensitive substring matching (entity names and brands). Confidence scores vary by alias type: identifier matches receive 0.9, legal name matches 0.85, general aliases 0.7, and brand matches 0.6. Multiple alias hits for the same entity are deduplicated, keeping the highest-confidence match and summing match counts. Detected mentions are persisted to the `document_company_mentions` table.
The normalized text and a structured parser output JSON (containing all metadata, quality signals, warnings, outbound links, tags, and mentions) are uploaded to the `app-normalized` MinIO bucket. The `documents` row is updated with the normalized storage reference, parser output reference, quality score, and confidence level.
Finally, the Parser makes a routing decision. If the document's `document_type` is `macro_event`, it is pushed onto `app:queue:macro_classification` for the Global Event Classifier agent. All other documents are pushed onto `app:queue:extraction` for the Document Intelligence Extractor agent. Both queues feed into the Extractor service described in [Page 2](02-ai-agent-processing-and-extraction.md). The job payload includes the `document_id`, `ticker`, and the first 32,000 characters of the normalized text, giving the downstream agent immediate access to the content without needing to fetch it from MinIO.
For additional detail on queue topology and data store layout, see the [Data Pipeline Architecture](../architecture-data-pipeline.md) documentation.
---
## What Comes Next
At this point, raw data has been fetched from four external sources, deduplicated, stored in MinIO, parsed into normalized text, scored for quality, tagged with entity mentions, and routed to the appropriate extraction queue. The documents sitting on `app:queue:extraction` and `app:queue:macro_classification` are clean, quality-filtered, and ready for AI processing. [Page 2 — AI Agent Processing and Structured Extraction](02-ai-agent-processing-and-extraction.md) picks up the story from here, explaining how the Document Intelligence Extractor and Global Event Classifier agents use LLM inference to transform these normalized documents into the structured JSON intelligence that feeds the rest of the pipeline.
@@ -0,0 +1,164 @@
# Page 2 — AI Agent Processing and Structured Extraction
Documents that arrive on the `app:queue:extraction` and `app:queue:macro_classification` Redis queues are clean, quality-filtered, and normalized — but they are still unstructured text. The job of the Extractor service is to transform that text into structured JSON intelligence that the rest of the pipeline can reason about quantitatively. Two AI agents share this responsibility: the Document Intelligence Extractor handles entity-specific content, filings, and transcripts, while the Global Event Classifier handles macro-level geopolitical and economic events. Both agents run through the same Ollama-based inference infrastructure, share a common JSON repair pipeline, and persist their results to PostgreSQL and MinIO for downstream consumption and audit.
This page explains how each agent works, what schemas they produce, how the system validates and repairs LLM output, how runtime configuration is resolved from the database, and how the final structured records are persisted. For a visual overview of the full flow from ingestion through extraction, see the [Ingestion to Extraction Flow diagram](diagrams/ingestion-to-extraction-flow.md). For reference-level detail on agent configuration and the variant management API, see the [AI Agents Guide](../ai-agents.md).
---
## The Document Intelligence Extractor
The Document Intelligence Extractor is the primary AI agent in the pipeline. Registered under the slug `document-extractor` in the `ai_agents` database table, it processes every non-macro document that passes through the Parser — news articles, regulatory filings, performance transcripts, and press releases. Its purpose is to read a normalized document and produce a structured JSON object that captures the document's summary, the entities it affects, the sentiment and impact for each entity, the catalysts driving that impact, and the evidence supporting the analysis.
The entry point is `services/extractor/main.py`, which runs a continuous worker loop polling the `app:queue:extraction` Redis list. When a job arrives, the worker extracts the `document_id`, `ticker`, and `text` fields from the JSON payload. If the job payload does not include the document text directly, the worker fetches it from MinIO using the `normalized_storage_ref` stored in the `documents` table — the Parser uploaded the normalized text to the `app-normalized` bucket during the previous pipeline stage (see [Page 1](01-data-ingestion-and-preparation.md)).
The actual LLM inference is handled by `OllamaClient` in `services/extractor/client.py`. The client sends the document to a local Ollama instance via the `/api/chat` HTTP endpoint with `stream=False` and `think=False`. The `think=False` flag is a deliberate performance choice — it disables the model's chain-of-thought reasoning phase, which would otherwise add two to four minutes of latency per document. The client does not use Ollama's `format` parameter for structured output because of a known Ollama bug (#14645) where the format constraint is silently ignored when `think=False` on qwen3.5 models. Instead, the system relies on prompt engineering to produce JSON and repairs any syntax issues after the fact.
The prompt sent to the model has two parts. The system prompt, defined in `services/extractor/prompts.py`, establishes the model's role as a document analyst and sets strict output rules: return only a single JSON object, no markdown fences, no explanation text, every schema field is required, use `"other"` for `catalyst_type` when unsure, keep evidence spans under 20 words, and limit key facts to three to five items. The user prompt, built by `build_extraction_prompt()` in the same module, provides the document text along with document-type-specific guidance. Four guidance variants exist — one each for articles, filings, transcripts, and press releases — each calibrated to the conventions and biases of that document type. For example, the filing guidance instructs the model to preserve the precise legal language of regulatory documents, while the press release guidance warns that sentiment may be biased positive and directs the model to focus on concrete metrics rather than marketing language.
The user prompt also includes a list of all tracked entity identifiers from the `companies` table, along with rules for how the model should use them. If a tracked entity identifier appears verbatim in the text, the model must include it in the output with at least one evidence span. If the article discusses a sector or theme that clearly affects a tracked entity (oil prices affecting Entity-D, AI chip demand affecting Entity-C), the model should include that entity as well. The model is explicitly told not to invent identifiers that are not in the provided list. Documents longer than 8,000 characters are truncated before being included in the prompt, with a `[... truncated for extraction ...]` marker appended.
The `OllamaClient` also supports a `context_window` override via the Ollama `num_ctx` option, which can be configured per agent variant through the `AgentConfigResolver` mechanism described later in this page.
---
## The ExtractionResult Schema
The structured output that the Document Intelligence Extractor produces is defined by the `ExtractionResult` Pydantic model in `services/extractor/schemas.py`. Every field is required — the model has no defaults — so the generated JSON schema forces the LLM to produce every field explicitly. The top-level fields are:
**`summary`** — a concise one-to-three sentence summary of the document's main point. This becomes the human-readable description stored in the `document_intelligence` table.
**`companies`** — an array of `CompanyExtractionItem` objects, one per affected entity. Each entity entry contains:
- `ticker` — the entity identifier (validated against a regex pattern of one to five uppercase letters).
- `company_name` — the full entity name as referenced in the document.
- `relevance` — a float between 0.0 and 1.0 indicating how relevant the document is to this entity, where 0 means tangential and 1 means the entity is the primary subject.
- `sentiment` — one of `positive`, `negative`, `neutral`, or `mixed`, representing the overall sentiment toward this entity in the document.
- `impact_score` — a float between 0.0 and 1.0 estimating the magnitude of impact, where 0 is negligible and 1 is highly material.
- `impact_horizon` — one of `intraday`, `1d`, `1d_7d`, `1d_30d`, `30d_90d`, or `90d_plus`, indicating the expected timeframe over which the impact will play out.
- `catalyst_type` — exactly one of `performance_report`, `product`, `legal`, `macro`, `supply_chain`, `m_and_a`, `rating_change`, or `other`. The prompt instructs the model to use `other` when none of the specific categories fit.
- `key_facts` — a list of facts explicitly stated in the document. The prompt emphasizes that the model must not infer or fabricate facts.
- `risks` — a list of risks explicitly mentioned in the document.
- `evidence_spans` — short verbatim quotes from the document supporting the analysis. The prompt requests these be kept under 20 words each.
**`macro_themes`** — a list of broad economic or environmental themes mentioned in the document, such as `rates`, `inflation`, or `ai_capex`.
**`novelty_score`** — a float between 0.0 and 1.0 indicating how novel or surprising the information is. Routine performance reports score low; unexpected regulatory actions score high. This value feeds into the novelty bonus component of the signal weighting formula described in [Page 3](03-signal-scoring-and-weighted-signals.md).
**`confidence`** — a float between 0.0 and 1.0 representing the model's confidence in the accuracy of its extraction. Lower values indicate ambiguous or incomplete source text. This value becomes the confidence gate input for signal scoring.
**`extraction_warnings`** — a list of issues encountered during extraction, such as `ambiguous_ticker`, `incomplete_text`, or `low_confidence`. These warnings are persisted alongside the intelligence record for operational monitoring.
The JSON schema is generated programmatically from the Pydantic models via `generate_json_schema()` in `services/extractor/schemas.py`, which calls Pydantic's `model_json_schema()` and then inlines all `$defs` references so the schema is self-contained and Ollama-friendly.
---
## The Global Event Classifier
Not all documents describe entity-specific developments. Macro news articles — those tagged with `document_type='macro_event'` by the Parser — describe events that affect entire sectors or economies: trade disputes, central bank rate decisions, commodity supply disruptions, geopolitical conflicts. These documents are routed to the `app:queue:macro_classification` Redis queue and processed by the Global Event Classifier agent, registered under the slug `event-classifier` in the `ai_agents` table.
The classifier is implemented in `services/extractor/event_classifier.py`. When the extractor worker in `services/extractor/main.py` pops a job and determines that the document type is `macro_event` (either because the job came from the macro queue or because the `documents` table records it as such), it routes the document to `_process_macro_classification()` instead of the standard extraction pipeline. This function calls `classify_global_event()`, which builds a dedicated prompt, sends it to Ollama through the same `OllamaClient` infrastructure, parses the response, and persists the result.
The classifier's system prompt is distinct from the extractor's. It establishes the model's role as a macro-level news classifier and includes explicit anti-hallucination rules that are critical to preventing the classifier from overreaching. The prompt states that the model should only classify articles about macro events that affect entire sectors or economies — trade disputes, interest rate changes, commodity supply disruptions, regulatory changes, geopolitical conflicts, natural disasters. It explicitly lists what should not be classified as macro events: individual entity performance reports, lawsuits against a single entity, single-entity management changes, individual entity analysis, entity-specific debt or bankruptcy, and product launches by one entity. For these entity-specific articles that were incorrectly routed, the model is instructed to set severity to `"low"`, confidence below 0.3, and leave the `affected_regions`, `affected_sectors`, and `affected_commodities` arrays empty.
The user prompt, built by `build_event_classification_prompt()`, reinforces these anti-hallucination rules and provides additional guidance. It instructs the model to only extract facts explicitly stated in the text, to set confidence below 0.4 for vague or speculative content, to distinguish announced policy from rumored policy, and to reserve `"critical"` severity for events affecting multiple countries or entire global systems. Articles longer than 6,000 characters are truncated before inclusion in the prompt.
The output schema is the `GlobalEvent` dataclass, which contains:
- `event_types` — a list of impact type strings, drawn from a fixed set: `supply_disruption`, `demand_shift`, `cost_increase`, `regulatory_pressure`, `currency_impact`, `commodity_shock`, `trade_barrier`, and `geopolitical_risk`. The model is instructed to include all applicable types rather than collapsing to a single category.
- `severity` — one of `low`, `moderate`, `high`, or `critical`.
- `affected_regions` — ISO 3166-1 alpha-2 country codes or region names (e.g., `US`, `CN`, `EU`, `GB`, `JP`). Only regions explicitly mentioned or clearly implied should be included.
- `affected_sectors` — GICS sector identifiers such as `Energy`, `Financials`, `Information Technology`, or `Industrials`.
- `affected_commodities` — commodity identifiers like `crude_oil`, `natural_gas`, `gold`, `copper`, `wheat`, `lithium`, or `semiconductors`. An empty list if no commodities are directly affected.
- `summary` — a one-to-three sentence summary of the event and its domain implications.
- `key_facts` — facts explicitly stated in the article, limited to three to five items.
- `estimated_duration` — one of `short_term` (days to weeks), `medium_term` (weeks to months), or `long_term` (months to years).
- `confidence` — a float between 0.0 and 1.0, clamped during parsing.
Each `GlobalEvent` also carries a `model_metadata` object recording the provider (`ollama`), model name, prompt version (`event-classification-v1`), and schema version (`1.0.0`), plus a `source_document_id` linking back to the originating document.
After a successful classification, the system computes macro impact records for all tracked entities using the exposure-based interpolation engine in `services/aggregation/interpolation.py`. Each entity's exposure profile — geographic revenue mix, supply chain regions, key input commodities, regulatory jurisdictions, and position tier — determines how much a given macro event affects that entity. Entities with non-zero macro impact scores get `macro_impact_records` rows persisted to PostgreSQL, and aggregation jobs are enqueued to `app:queue:aggregation` for each affected entity identifier. The extractor worker tracks consecutive macro classification failures and emits a critical-level alert after three consecutive failures, continuing with entity-only signals in the meantime.
---
## The JSON Repair Pipeline
LLM output is inherently unreliable at the syntactic level. Models sometimes wrap JSON in markdown fences, produce trailing commas, leave strings unterminated, or truncate output mid-object when they hit token limits. The extractor addresses this with a three-stage JSON repair pipeline implemented across `services/extractor/client.py` and `services/extractor/schemas.py`.
The first stage is a direct `json.loads()` call. If the raw model output is already valid JSON, no repair is needed and the pipeline moves straight to validation. This is the fast path for well-behaved model responses.
The second stage strips markdown fences. Models frequently wrap their output in `` ```json ... ``` `` blocks despite being told not to. The `_strip_markdown_fences()` function in `services/extractor/client.py` uses a regex to detect and remove these wrappers before attempting another parse.
The third stage invokes the `json-repair` library as a fallback. The `_repair_json()` function in `services/extractor/client.py` calls `repair_json()` with `return_objects=False` to get a repaired JSON string. This library handles a wide range of common LLM JSON errors — trailing commas, missing quotes, unescaped characters — that would otherwise require custom repair logic.
The `services/extractor/schemas.py` module contains an additional layer of repair logic in its own `_repair_json()` function, which handles cases that the library might miss. It strips non-JSON prefixes (models sometimes prepend explanatory text before the opening brace), removes control characters that break parsing, fixes trailing commas before closing brackets, and as a last resort calls `_repair_truncated_json()` — a state-machine parser that walks the string tracking bracket depth and string state, then appends the necessary closing tokens to complete a truncated JSON object.
For the Global Event Classifier, the `_parse_classification_response()` function in `services/extractor/event_classifier.py` reuses the same `_strip_markdown_fences()` and `_repair_json()` functions from the client module, and additionally handles the case where the model wraps the output object in a single-element list — a quirk observed with some model configurations.
---
## Structural and Semantic Validation
Repairing JSON syntax is only the first step. The `validate_extraction()` function in `services/extractor/schemas.py` performs both structural and semantic validation on the parsed output, and the distinction between the two is important for understanding the retry logic.
Structural validation begins with normalization. The `_normalize_extraction_data()` function fills in missing top-level fields with sensible defaults (empty summary, empty companies array, 0.5 novelty score, 0.3 confidence), clamps numeric fields to the [0.0, 1.0] range, and normalizes per-entity fields. Catalyst types that the model produces as free-text alternatives — `"strategic pivot"`, `"acquisition"`, `"lawsuit"`, `"inflation"`, `"launch"` — are mapped to their canonical enum values through a comprehensive alias dictionary. Impact horizons like `"long-term"`, `"short"`, `"immediate"`, or `"near-term"` are similarly mapped to the valid set (`intraday`, `1d`, `1d_7d`, `1d_30d`, `30d_90d`, `90d_plus`). After normalization, the data is validated against the `ExtractionResult` Pydantic model, which enforces type constraints, enum membership, and range bounds.
Semantic validation catches issues that are structurally valid but logically suspect. The `_semantic_checks()` function runs a series of cross-field consistency checks that produce either errors (which trigger a retry) or warnings (which are logged but do not block acceptance). Semantic errors include duplicate entity identifiers across entity entries, missing identifier fields, and invalid impact horizon values. Semantic warnings include empty summaries, low confidence with entities present, invalid identifier formats (not matching the one-to-five uppercase letter pattern), missing evidence spans, evidence spans that are too short (under 8 characters) or too long (over 500 characters), high impact scores with no supporting key facts, very low relevance scores, and strong sentiment paired with negligible impact scores.
When the original document text is available, the validator also performs an evidence grounding check: each evidence span is searched for in the source text (case-insensitive), and spans not found in the document are flagged with a warning. This helps detect hallucinated evidence — quotes the model fabricated rather than extracted from the actual text.
If validation produces any semantic errors, the `ValidationReport` is marked as invalid and the `OllamaClient` retry loop treats it as a failed attempt. The retry logic uses exponential backoff with configurable parameters: a base delay (default from `OllamaConfig`), a multiplier applied on each retry, and a maximum delay cap. The number of retries is configurable per agent through the `max_retries` field in the `ai_agents` or `agent_variants` table. Non-retryable errors — HTTP 400, 401, 403, 404, and 422 responses from Ollama — short-circuit the retry loop immediately, since these indicate a problem with the request itself rather than a transient model failure.
Every attempt, whether successful or not, is recorded in an `ExtractionAttempt` dataclass that captures the raw output, validation report, error description, duration in milliseconds, model name, and whether the error was retryable. The full list of attempts is preserved in the `ExtractionResponse` for audit purposes and uploaded to MinIO by the persistence layer.
---
## The AgentConfigResolver: Hot-Swapping Models and Prompts
Both the Document Intelligence Extractor and the Global Event Classifier resolve their runtime configuration through the `AgentConfigResolver` in `services/shared/agent_config.py`. This mechanism allows operators to change models, prompts, timeouts, retry counts, and token budgets without restarting any service — changes take effect within 60 seconds.
The resolver works by querying the `ai_agents` and `agent_variants` PostgreSQL tables with a single SQL statement that uses `COALESCE` to prefer variant values over base agent values. When the extractor worker starts, it creates an `AgentConfigResolver` instance with a 60-second TTL cache and calls `resolver.resolve("document-extractor")` to get the active configuration. If an active variant exists for the agent (enforced by a unique partial index on `agent_variants` that allows at most one active variant per agent), the variant's `model_name`, `system_prompt`, `temperature`, `max_tokens`, `context_window`, `timeout_seconds`, and `max_retries` override the base agent's values wherever the variant provides a non-NULL value. If no active variant exists, the base agent's configuration is used. If the database query fails entirely, the resolver returns `None` and the worker falls back to environment-variable-based `OllamaConfig` defaults.
The resolved configuration is captured in a `ResolvedAgentConfig` frozen dataclass that includes the `agent_id`, `variant_id` (if any), `model_provider`, `model_name`, `system_prompt`, `user_prompt_template`, `prompt_version`, `temperature`, `max_tokens`, `context_window`, `input_token_limit`, `token_budget`, `timeout_seconds`, and `max_retries`. The extractor worker uses this to build an `OllamaConfig` that is passed to the `OllamaClient`.
The 60-second TTL cache means the resolver only hits the database once per minute per agent slug. Cache entries are keyed by slug and timestamped with `time.monotonic()`. When a cached entry expires, the next `resolve()` call re-queries the database and refreshes the cache. The `invalidate()` method can clear a single slug or the entire cache, though in practice the TTL-based expiry is sufficient for normal operations.
The extractor worker re-resolves its configuration every 100 jobs. If the resolved model name has changed (for example, because an operator activated a variant that uses a different model), the worker closes the old `OllamaClient` and creates a new one with the updated configuration. The event classifier is resolved separately and can use a different model than the document extractor — the worker maintains two independent `OllamaClient` instances when the models differ.
Token budget enforcement adds another layer of control. If a variant specifies a `token_budget` (total tokens per hour), the worker checks the `agent_performance_log` table before each invocation to see whether the budget has been exceeded. If so, the invocation is skipped entirely. Input token limits work similarly: if a variant sets an `input_token_limit`, the worker truncates the document text to approximately that many tokens (estimated at four characters per token) before sending it to the model.
For a complete guide to creating variants, activating them, and comparing their performance, see the [AI Agents Guide](../ai-agents.md).
---
## Persistence: From Extraction to Database
Once the LLM produces a valid extraction and it passes validation, the `persist_extraction()` function in `services/extractor/worker.py` orchestrates the full persistence pipeline. This function writes to both MinIO (for audit) and PostgreSQL (for downstream consumption), ensuring that every extraction attempt is fully traceable.
The MinIO persistence layer uploads four artifacts per extraction, all stored under date-partitioned paths in dedicated buckets. The prompt metadata (prompt version, schema version, model name) goes to `app-llm-prompts`. The raw model output for every attempt — including failed ones — goes to `app-llm-results`, preserving the full retry history. A validation report summarizing the final attempt's status, errors, and warnings is uploaded alongside the raw output. On success, the final parsed intelligence object (the `ExtractionResult` serialized as JSON) is uploaded to a separate path for easy retrieval.
The PostgreSQL persistence writes to two tables. The `document_intelligence` table receives one row per document, containing the summary, macro themes, novelty score, source credibility, extraction warnings, confidence, model metadata (provider, model name, prompt version, schema version), references to the MinIO artifacts (raw output ref, prompt ref), validation status (`valid` or `failed`), validation errors, and retry count. This row is the authoritative record of what the AI extracted from the document.
The `document_impact_records` table receives one row per entity mention within the extraction. Each impact record is linked to the parent `document_intelligence` row via `intelligence_id` and to the `companies` table via `company_id`. The record captures the entity identifier, relevance, sentiment, impact score, impact horizon, catalyst type, key facts, risks, and evidence spans for that specific entity. The `company_id` is resolved from an identifier-to-UUID mapping that the worker maintains by querying the `companies` table (refreshed every 100 jobs). If an identifier in the extraction output does not match any tracked entity, the impact record is skipped with a warning — the system only persists impact records for entities in its tracked universe.
After persisting the intelligence and impact records, the worker updates the document's status in the `documents` table to `extracted` (or `extraction_failed` if all retry attempts were exhausted). Even failed extractions get a `document_intelligence` row with `validation_status='failed'`, empty summary, zero confidence, and the accumulated error messages — this ensures the failure is visible in the database rather than silently lost.
Performance metrics are collected for every extraction via `collect_metrics()` in `services/extractor/metrics.py` and persisted to a metrics table. Prometheus counters and histograms track extraction attempts, duration, retries, confidence distribution, validation errors, and estimated token usage (input and output, estimated at four characters per token). When a resolved agent config is available, the worker also logs to the `agent_performance_log` table with variant attribution, enabling the A/B comparison queries described in the [AI Agents Guide](../ai-agents.md).
For the Global Event Classifier, persistence follows a parallel path. The prompt and raw output are uploaded to MinIO under an `event_classification/macro/` path prefix. The parsed `GlobalEvent` is persisted to the `global_events` PostgreSQL table, which stores the event types, severity, affected regions, affected sectors, affected commodities, summary, key facts, estimated duration, confidence, source document ID, and model metadata. Downstream, the macro interpolation engine computes `macro_impact_records` for each affected entity and persists those as well.
---
## Enqueuing Aggregation Jobs
The final step in the extraction pipeline is to notify the downstream aggregation engine that new intelligence is available. After a successful document extraction, the worker pushes a job onto the `app:queue:aggregation` Redis list containing the identifier of the affected entity. The aggregation engine (described in [Page 3](03-signal-scoring-and-weighted-signals.md)) will pick up this job and recompute the weighted signals and trend summaries for that entity, incorporating the freshly extracted intelligence.
For macro events, the enqueue logic is more expansive. After the Global Event Classifier produces a `GlobalEvent` and the interpolation engine computes macro impact records, the worker enqueues an aggregation job for every entity identifier that received a non-zero macro impact score. A single macro event — say, a new regulatory policy change affecting the Energy and Industrials sectors — can trigger aggregation recomputation for dozens of entities simultaneously. The aggregation job payload includes both the entity identifier and the `macro_event_id`, so the aggregation engine knows to incorporate the new macro signals.
The worker alternates between the extraction and macro classification queues to prevent starvation: every third job is pulled from `app:queue:macro_classification`, with the remaining two-thirds from `app:queue:extraction`. If the preferred queue is empty, the worker falls back to the other queue, ensuring that neither pipeline stalls while the other has work available.
---
## What Comes Next
At this point, documents have been transformed from unstructured text into structured JSON intelligence — `ExtractionResult` objects for entity-specific documents and `GlobalEvent` objects for macro news. These structured records are persisted in PostgreSQL and their entity identifiers have been enqueued for aggregation. But raw extraction output is not yet actionable for downstream decisions. The extraction tells us that a document is negative for Entity-A with an impact score of 0.7 and a confidence of 0.8, but it does not tell us how much weight that signal should carry relative to other signals about Entity-A, or how it compares to signals from different sources, time periods, or environmental conditions. [Page 3 — Signal Scoring and the WeightedSignal Abstraction](03-signal-scoring-and-weighted-signals.md) picks up the story from here, explaining how the aggregation engine transforms these raw extraction outputs into weighted signals through confidence gating, recency decay, source credibility scoring, novelty bonuses, and environmental context multipliers.
@@ -0,0 +1,210 @@
# Page 3 — Signal Scoring and the WeightedSignal Abstraction
The extraction pipeline described in [Page 2](02-ai-agent-processing-and-extraction.md) produces structured intelligence records — `document_impact_records` for entity-specific documents, `macro_impact_records` for global events, and `competitive_signal_records` for cross-entity pattern propagation. Each record carries a sentiment, an impact score, a confidence value, and a publication timestamp. But these raw values are not directly comparable. A high-confidence extraction from a reputable source published ten minutes ago should carry far more weight than a low-confidence extraction from an unknown source published three weeks ago. A document that breaks genuinely novel information should matter more than one that rehashes yesterday's performance report. And when conditions are changing fast — high volatility, surging volume — fresh signals become even more critical.
The signal scoring layer in `services/aggregation/scoring.py` solves this problem by transforming each raw intelligence record into a `WeightedSignal` object: a document reference paired with a composite aggregation weight that encodes recency, credibility, novelty, confidence, and environmental conditions into a single number. This page explains how that weight is computed, how sentiment labels become numeric values, and how three independent signal layers — Entity-Specific, Macro, and Competitive — each produce `WeightedSignal` objects that are concatenated into a unified list before the aggregation engine computes trend summaries. For a visual breakdown of the composite weight formula, see the [Weighted Signal Computation diagram](diagrams/weighted-signal-computation.md). For the full picture of how the three layers merge, see the [Three-Layer Signal Merging diagram](diagrams/three-layer-signal-merging.md).
---
## The WeightedSignal and SignalWeight Dataclasses
The core abstraction is the `WeightedSignal` dataclass, defined in `services/aggregation/scoring.py`. It pairs a document reference with the computed weight and the signal's sentiment and impact values:
- **`document_id`** — the UUID of the source document (for entity-specific and macro signals) or a synthetic identifier for pattern-derived signals (e.g., `pattern:Entity-A:performance_report:7d`).
- **`weight`** — a `SignalWeight` object containing the component breakdown and the final combined score.
- **`sentiment_value`** — a numeric sentiment value: `+1.0` for positive, `-1.0` for negative, `0.0` for neutral or mixed.
- **`impact_score`** — the magnitude of impact, drawn from the extraction's per-entity impact score for entity-specific signals, or scaled by a layer-specific weight multiplier for macro and competitive signals.
The `SignalWeight` dataclass captures the individual components that feed into the combined weight, making the scoring decision fully transparent and auditable:
- **`recency`** — the exponential decay weight based on document age.
- **`credibility`** — the source credibility weight after clamping and exponentiation.
- **`novelty_bonus`** — the additive bonus derived from the document's novelty score.
- **`confidence_gate`** — either `1.0` (signal passes) or `0.0` (signal is gated out).
- **`market_ctx_multiplier`** — a multiplicative boost from environmental conditions, always `>= 1.0`.
- **`combined`** — the final composite weight used by the aggregation engine.
The `ScoringConfig` frozen dataclass holds all tunable parameters for the scoring functions — half-life hours per window, credibility bounds, novelty bonus cap, confidence floor, and environmental context thresholds. A module-level `DEFAULT_CONFIG` singleton provides the production defaults, but every scoring function accepts an optional `config` parameter so that tests and alternative configurations can override any parameter without modifying global state.
---
## The Composite Weight Formula
The `compute_signal_weight()` function in `services/aggregation/scoring.py` computes the combined weight for a single document signal. The formula is:
```
combined = gate × recency × credibility × (1 + novelty_bonus) × market_context_multiplier
```
Each factor is computed independently and then multiplied together. This multiplicative structure means that any single factor can zero out the entire weight (the confidence gate) or amplify it (the market context multiplier), and the interaction between factors is naturally captured — a highly credible, very recent document with novel information in a volatile environment receives the maximum possible weight, while a stale, low-credibility document with routine information receives a weight close to zero.
The following sections describe each component in detail.
---
## Confidence Gate
The confidence gate is the first and most decisive filter. If the extraction confidence for a document falls below the `confidence_floor` threshold — set to `0.2` in the default `ScoringConfig` — the gate evaluates to `0.0` and the entire combined weight becomes zero. The document is effectively excluded from aggregation. If the confidence meets or exceeds the threshold, the gate evaluates to `1.0` and has no further effect on the weight.
This binary gate exists because documents with very low extraction confidence are too unreliable to aggregate. A confidence of 0.15 typically means the LLM struggled to parse the document — perhaps the text was truncated, the language was ambiguous, or the document type was unusual. Including such signals would add noise rather than information. The threshold of 0.2 is deliberately low; it filters only the most unreliable extractions while allowing moderately confident signals to participate (their lower confidence is reflected through the credibility component instead).
---
## Recency Decay
The `recency_weight()` function computes an exponential decay based on how old a document is relative to the aggregation anchor time. The formula is:
```
w = 2^(age_hours / half_life)
```
A document published exactly one half-life ago receives a recency weight of `0.5`. A document published two half-lives ago receives `0.25`, and so on. A document published at or after the reference time receives the maximum weight of `1.0`.
The half-life varies by trend window, reflecting the intuition that shorter windows need faster decay to stay responsive, while longer windows should give older documents more influence. The default half-lives, configured in `ScoringConfig.half_life_hours`, are:
| Window | Half-Life |
|--------|-----------|
| `intraday` | 2 hours |
| `1d` | 12 hours |
| `7d` | 72 hours (3 days) |
| `30d` | 240 hours (10 days) |
| `90d` | 720 hours (30 days) |
For the intraday window, a document published four hours ago already has a recency weight of `0.25` — it is rapidly losing influence as newer information arrives. For the 90-day window, that same four-hour-old document still has a recency weight of essentially `1.0`, because the 30-day half-life means age only becomes significant over weeks.
A floor value of `min_recency_weight = 0.01` prevents very old documents from being completely zeroed out. Even a document from months ago retains a trace-level weight of 1%, ensuring it can still contribute to trend computation if no newer signals exist. Both timestamps are normalized to UTC; naive datetimes are treated as UTC to avoid timezone-related scoring errors.
---
## Source Credibility
The `credibility_weight()` function transforms a source's credibility score into a weight component. The raw credibility value — a float between 0.0 and 1.0 stored in the `document_intelligence` table — is first clamped to the range `[0.1, 1.0]` using the `credibility_floor` and `credibility_ceiling` parameters from `ScoringConfig`. This clamping ensures that even the least credible sources retain a minimum weight of 0.1 rather than being completely silenced, while preventing any source from exceeding a weight of 1.0.
After clamping, the value is raised to the `credibility_exponent` power. The default exponent is `1.0`, which means the clamped credibility passes through unchanged. Setting the exponent above 1.0 would penalize low-credibility sources more aggressively — for example, an exponent of 2.0 would reduce a credibility of 0.5 to a weight of 0.25. Setting it below 1.0 would flatten the curve, making the system more tolerant of lower-credibility sources. The exponent is configurable through `ScoringConfig` to allow operators to tune the credibility sensitivity without changing the scoring code.
---
## Novelty Bonus
The novelty bonus rewards documents that contain genuinely new information. The bonus is computed as:
```
novelty_bonus = novelty_score × novelty_bonus_max
```
where `novelty_score` is the 0.0-to-1.0 value produced by the extraction model (see the `ExtractionResult` schema in [Page 2](02-ai-agent-processing-and-extraction.md)) and `novelty_bonus_max` is `0.25` by default. This means the bonus ranges from `0.0` (completely routine information) to `0.25` (maximally novel information), providing up to a 25% boost to the signal weight.
The bonus enters the composite formula as `(1 + novelty_bonus)`, so it acts as a multiplicative amplifier on the base weight. A document with a novelty score of 1.0 gets its weight multiplied by 1.25; a document with a novelty score of 0.0 gets multiplied by 1.0 (no change). This design ensures that novelty can only increase a signal's weight, never decrease it — routine information is not penalized, it simply does not receive the bonus.
---
## Environmental Context Multiplier
The `market_context_multiplier()` function computes a boost factor based on real-time environmental conditions for the entity being aggregated. The multiplier is always `>= 1.0`, meaning environmental context can only amplify signal weights, never reduce them. When no environmental context data is available (the `MarketContext` object from `services/shared/schemas.py` has `has_data == False`), the multiplier defaults to `1.0`.
Two environmental features contribute to the boost:
**Volatility boost.** When the entity's price volatility exceeds the `volatility_recency_boost_threshold` (default `1.0` in price units), the excess volatility is transformed through a logarithmic scaling function: `log₁₊(excess) × 0.15`. The logarithmic scaling prevents extreme volatility from producing runaway weight amplification. The boost is capped at `volatility_recency_boost_max = 0.30`, so the maximum volatility contribution is a 30% weight increase. The rationale is that in highly volatile environments, fresh intelligence is disproportionately valuable — a signal about Entity-C matters more when Entity-C is swinging 5% intraday than when it is moving in a tight range.
**Volume surge boost.** When the entity's volume change percentage exceeds `volume_surge_threshold_pct = 50.0%` (meaning activity volume is at least 50% above the prior period's average), a flat `volume_surge_boost = 0.15` is added. Unlike the volatility boost, this is binary — either the volume threshold is met and the full 15% boost applies, or it is not and no boost is added. High-volume moves carry more conviction because they represent broader participation rather than thin-activity noise.
The two boosts are additive within the multiplier: `multiplier = 1.0 + volatility_boost + volume_surge_boost`. In the most extreme case — high volatility and a volume surge — the combined multiplier reaches `1.0 + 0.30 + 0.15 = 1.45`, amplifying the signal weight by 45%. The `MarketContext` data is fetched by `services/aggregation/market_context.py` from the data tables in PostgreSQL, using the same entity identifier and window parameters as the impact record query.
---
## Sentiment Mapping
Before signals can be aggregated into trend summaries, the categorical sentiment labels from the extraction output must be converted to numeric values. The `sentiment_to_numeric()` function in `services/aggregation/scoring.py` performs this mapping:
| Sentiment Label | Numeric Value |
|----------------|---------------|
| `positive` | `+1.0` |
| `negative` | `-1.0` |
| `neutral` | `0.0` |
| `mixed` | `0.0` |
The mapping is case-insensitive. Any unrecognized label defaults to `0.0`. The choice to map both `neutral` and `mixed` to `0.0` is deliberate — a mixed-sentiment document (one that contains both positive and negative signals for the same entity) should not push the trend in either direction. The contradiction between the positive and negative aspects is captured separately by the contradiction detection system described in [Page 4](04-trend-aggregation-and-accumulating-signals.md), rather than being baked into the sentiment value itself.
For macro signals, the direction-to-sentiment mapping in `services/aggregation/worker.py` follows the same pattern: `positive` maps to `+1.0`, `negative` to `-1.0`, and both `mixed` and `neutral` to `0.0`. For competitive signals built by `build_pattern_weighted_signals()` in `services/aggregation/signal_propagation.py`, the sentiment is derived from the pattern's directional bias: `+1.0` if `positive_pct > negative_pct`, `-1.0` otherwise.
---
## Weighted Sentiment Average
The `weighted_sentiment_average()` function computes the central metric that drives trend direction: a weight-adjusted average sentiment across all signals for an entity in a given window. The formula is:
```
weighted_avg = Σ(combined_weight × impact_score × sentiment_value) / Σ(combined_weight × impact_score)
```
Each signal contributes its sentiment value scaled by both its composite weight and its impact score. The denominator normalizes by the total effective weight, producing a value in the range `[-1.0, +1.0]`. A result near `+1.0` means the weighted evidence is overwhelmingly positive; near `-1.0` means overwhelmingly negative; near `0.0` means either neutral or evenly split.
The use of `combined_weight × impact_score` as the effective weight means that high-impact, high-weight signals dominate the average. A single high-confidence, recent, credible document with a strong impact score can outweigh several older, lower-impact documents — which is the intended behavior. The aggregation engine in `services/aggregation/worker.py` passes this weighted average to `derive_trend_direction()`, which maps it to a `TrendDirection` enum value (positive, negative, mixed, or neutral) using the thresholds described in [Page 4](04-trend-aggregation-and-accumulating-signals.md).
If the total effective weight is zero — either because no signals exist or all signals were gated out by the confidence floor — the function returns `0.0`, which maps to a neutral trend direction.
---
## The Three Signal Layers
The aggregation engine in `services/aggregation/worker.py` does not treat all intelligence sources equally. Signals flow through three independent layers, each with a different relative weight, before being concatenated into a single `WeightedSignal` list for trend computation. This layered architecture allows the system to incorporate diverse intelligence sources while controlling how much influence each source type has on the final trend.
### Layer 1 — Entity-Specific Signals (Weight: 1.0)
Entity-specific signals are the primary layer. They are built by `build_weighted_signals()` in `services/aggregation/worker.py` from `document_impact_records` — the per-entity extraction output produced by the Document Intelligence Extractor (see [Page 2](02-ai-agent-processing-and-extraction.md)). Each impact record's sentiment is converted via `sentiment_to_numeric()`, and its impact score is used directly without any layer-level scaling. The `compute_signal_weight()` function produces the composite weight using the document's publication time, source credibility, novelty score, extraction confidence, and the entity's current environmental context.
Entity-specific signals carry a relative weight of `1.0` — they are the baseline against which other layers are measured. This reflects the design principle that direct, entity-specific intelligence (a performance report about Entity-A, a product launch by Entity-B, a lawsuit against Entity-E) is the most relevant and reliable signal for that entity's trend.
### Layer 2 — Macro Signals (Weight: 0.3)
Macro signals capture the indirect impact of global events on individual entities. They are built by `build_macro_weighted_signals()` in `services/aggregation/worker.py` from `macro_impact_records` — the per-entity impact scores computed by the exposure-based interpolation engine after the Global Event Classifier processes a macro news article. The sentiment is mapped from the `impact_direction` field (`positive``+1.0`, `negative``-1.0`, `mixed`/`neutral``0.0`), and the impact score is scaled by `MACRO_SIGNAL_WEIGHT`, which defaults to `0.3` in `AggregationConfig`.
The 0.3 weight means that a macro signal's impact score is reduced to 30% of its raw value before entering the aggregation. This attenuation reflects the inherent uncertainty in macro-to-entity impact estimation — a policy change might affect Entity-D's revenue, but the magnitude depends on exposure profiles, supply chain flexibility, and competitive dynamics that the interpolation engine can only approximate. By weighting macro signals at 0.3 relative to entity-specific signals at 1.0, the system ensures that macro intelligence informs the trend without overwhelming direct entity-specific evidence.
The recency decay, credibility, and confidence gating for macro signals use the same `compute_signal_weight()` function as entity-specific signals. The `published_at` timestamp comes from the global event's source document (the macro news article), and the `source_credibility` and `extraction_confidence` both use the macro impact record's `confidence` field.
### Layer 3 — Competitive Signals (Weight: 0.2)
Competitive signals capture cross-entity effects: when a catalyst hits one entity, historical patterns suggest how competitors might be affected. They are built by `build_pattern_weighted_signals()` in `services/aggregation/signal_propagation.py` from two sources: `HistoricalPattern` objects (self-entity patterns mined by `services/aggregation/pattern_matcher.py`) and `CompetitiveSignalRecord` objects (cross-entity propagation signals stored in `competitive_signal_records`).
For historical patterns, the sentiment is derived from the pattern's directional bias (`+1.0` if `positive_pct > negative_pct`, `-1.0` otherwise), and the impact score is the pattern's `avg_strength` multiplied by `competitive_signal_weight` (default `0.2` from `CompetitiveConfig`). The `published_at` for recency decay uses the pattern's `data_end` — the most recent data point in the pattern's sample — and the `extraction_confidence` uses the pattern's `pattern_confidence`. Source credibility is set to `1.0` because patterns are derived from validated historical data, and novelty is fixed at `0.5`.
For competitive signal records, the same structure applies: sentiment from `signal_direction`, impact from `signal_strength × competitive_signal_weight`, recency from `computed_at`, and confidence from `pattern_confidence`.
The 0.2 weight makes competitive signals the lightest layer. This is appropriate because competitive signal propagation involves the most inference — the system is predicting how Entity B will react based on what happened to Entity A in historically similar situations. The signal is valuable as supplementary evidence but should not drive trend direction on its own.
---
## Signal Merging in the Aggregation Engine
The `aggregate_company_window()` function in `services/aggregation/worker.py` orchestrates the merging of all three layers for a single entity and window. The process follows a clear sequence:
1. **Fetch entity-specific impact records** from `document_impact_records` for the entity within the window's time range.
2. **Fetch environmental context** for the entity from data tables.
3. **Build entity-specific weighted signals** via `build_weighted_signals()`.
4. **Check the macro toggle** — query `risk_configs` for the `macro_enabled` flag, then fetch and merge macro signals if enabled.
5. **Check the competitive toggle** — query `risk_configs` for the `competitive_enabled` flag, then fetch patterns, fetch competitive signals, and merge if enabled.
6. **Concatenate** all `WeightedSignal` lists into a single list.
7. **Assemble the `TrendSummary`** from the merged signals.
The concatenation in step 6 is a simple list append — `signals = signals + macro_signals` followed by `signals = signals + pattern_weighted`. There is no re-weighting or normalization at the merge point. The relative influence of each layer is already encoded in the impact scores (scaled by 0.3 for macro, 0.2 for competitive, 1.0 for entity-specific) and in the composite weights computed by `compute_signal_weight()`. The `weighted_sentiment_average()` function then naturally produces a sentiment average that reflects these relative weights.
---
## Runtime Toggles and Graceful Degradation
Both the macro and competitive signal layers can be enabled or disabled at runtime through the `risk_configs` PostgreSQL table, without restarting any service. The toggle state is read fresh from the database at the start of every aggregation cycle — there is no caching — so changes take effect on the very next cycle.
The `fetch_macro_enabled()` function in `services/aggregation/worker.py` queries the most recent active `risk_configs` row and reads the `config->>'macro_enabled'` JSON field. If the field is explicitly set to `"true"` or `"false"`, that value overrides the `AggregationConfig` default. If no config row exists or the field is absent, the function returns `None` and the engine falls back to the `AggregationConfig.macro_enabled` default (which is `True`). The `fetch_competitive_enabled()` function follows the identical pattern for the `competitive_enabled` field.
When a layer is disabled, the aggregation engine simply skips the fetch-and-merge step for that layer. Entity-specific signals are always computed — they cannot be toggled off. This means the system degrades gracefully: disabling the macro layer produces trends based on entity-specific signals alone (plus competitive signals if enabled), and disabling the competitive layer produces trends based on entity-specific and macro signals. Disabling both layers reduces the engine to its original single-layer behavior, using only direct document intelligence.
Crucially, disabling a layer does not stop upstream processing. When the macro layer is disabled, the Global Event Classifier continues to classify macro events and the interpolation engine continues to compute `macro_impact_records`. The data accumulates in PostgreSQL. When the layer is re-enabled, the aggregation engine immediately picks up all the macro impact records that were computed while the layer was disabled — there is no data loss or gap in coverage. The same applies to competitive signals: pattern mining and signal propagation continue regardless of the toggle state.
If the competitive signal fetch fails at runtime (for example, due to a database timeout), the aggregation engine catches the exception, logs it, and continues with entity-specific and macro signals only. This exception-based graceful degradation ensures that a transient failure in one layer does not block trend computation entirely.
---
## What Comes Next
At this point, every document intelligence record, macro impact record, and competitive signal record has been transformed into a `WeightedSignal` with a composite weight that encodes recency, credibility, novelty, confidence, and environmental conditions. The three signal layers have been merged into a single list, and the weighted sentiment average has been computed. But a single aggregation cycle produces only a snapshot — a point-in-time view of the evidence. The real power of the system emerges when these snapshots accumulate across multiple documents and time windows, building a case for action. [Page 4 — Trend Aggregation and Accumulating Signals](04-trend-aggregation-and-accumulating-signals.md) explains how the aggregation engine computes `TrendSummary` objects across five time windows, how consecutive same-direction signals strengthen trend confidence and escalate the system's response from neutral observation to actionable decision recommendations, and how contradiction detection and evidence ranking ensure that the trend reflects genuine consensus rather than noise.
@@ -0,0 +1,267 @@
# Page 4 — Trend Aggregation and Accumulating Signals
The scoring layer described in [Page 3](03-signal-scoring-and-weighted-signals.md) transforms every intelligence record into a `WeightedSignal` — a document reference paired with a composite weight that encodes recency, credibility, novelty, confidence, and environmental conditions. Three independent signal layers (Entity-Specific at weight 1.0, Environmental at 0.3, Relational at 0.2) each produce `WeightedSignal` objects that are concatenated into a single list. But a single list of weighted signals is still just raw material. The aggregation engine in `services/aggregation/worker.py` is where that raw material becomes a decision-grade assessment: a `TrendSummary` object that captures the direction, strength, confidence, contradiction level, and supporting evidence for an entity across a specific time window. This page explains how that transformation works — from weighted sentiment averages through trend direction derivation, contradiction detection, evidence ranking, and confidence computation — and, critically, how consecutive signals pointing in the same direction accumulate across documents and time windows to escalate the system's response from passive observation to actionable decision recommendations.
For a visual overview of the accumulation and escalation process, see the [Trend Accumulation and Escalation diagram](diagrams/trend-accumulation-escalation.md). For how the three signal layers merge into the aggregation engine, see the [Three-Layer Signal Merging diagram](diagrams/three-layer-signal-merging.md).
---
## Five Time Windows
The aggregation engine does not compute a single trend for each entity. It computes five, one for each time window defined in `services/aggregation/worker.py`:
| Window | Lookback Duration |
|--------|-------------------|
| `intraday` | 12 hours |
| `1d` | 1 day |
| `7d` | 7 days |
| `30d` | 30 days |
| `90d` | 90 days |
Each window produces an independent `TrendSummary` by fetching all impact records, macro impacts, and competitive signals for the entity within that window's time range. The `aggregate_company_window()` function in `services/aggregation/worker.py` orchestrates this per-window computation: it determines the time range from the window's lookback duration, fetches `document_impact_records` from PostgreSQL, retrieves environmental context, builds entity-specific weighted signals, checks the macro and competitive runtime toggles (see [Page 3](03-signal-scoring-and-weighted-signals.md) for toggle details), merges any enabled layer signals, and then assembles the `TrendSummary`.
The five-window design serves a specific purpose. Short windows (intraday, 1d) capture fast-moving sentiment shifts — a breaking negative performance disclosure, a sudden regulatory action — while long windows (30d, 90d) reveal sustained trends that persist across many documents and data cycles. An entity might show a negative intraday trend after a single unfavorable article, but a neutral 30-day trend because the broader evidence base is balanced. The recommendation engine downstream (described in [Page 5](05-recommendation-generation.md)) evaluates each window's `TrendSummary` independently, so the system can respond to both short-term catalysts and long-term directional shifts.
The `aggregate_company()` function iterates over all effective windows (configurable via `AggregationConfig.windows`, defaulting to all five) and calls `aggregate_company_window()` for each one. This means a single aggregation cycle for one entity produces up to five `TrendSummary` objects, each reflecting a different temporal perspective on the same underlying evidence.
---
## Trend Direction Derivation
Once the weighted sentiment average has been computed from the merged signal list (see the `weighted_sentiment_average()` function described in [Page 3](03-signal-scoring-and-weighted-signals.md)), the `derive_trend_direction()` function in `services/aggregation/worker.py` maps that numeric value to a `TrendDirection` enum. The rules are evaluated in a specific order, and the first matching rule wins:
1. **Mixed** — If the contradiction score exceeds `0.10` (the `MIXED_THRESHOLD` constant) *and* the absolute value of the average sentiment is below `0.30`, the direction is `MIXED`. This rule fires first because high contradiction with a weak directional signal indicates genuine disagreement in the evidence — the trend is not simply neutral, it is actively contested.
2. **Positive** — If the average sentiment is `≥ 0.15` (the `POSITIVE_THRESHOLD` constant), the direction is `POSITIVE`. This means the weight-adjusted evidence leans favorable with enough conviction to cross the threshold.
3. **Negative** — If the average sentiment is `≤ -0.15` (the `NEGATIVE_THRESHOLD` constant), the direction is `NEGATIVE`. The symmetric threshold ensures that positive and negative classifications require the same magnitude of evidence.
4. **Neutral** — If none of the above conditions are met, the direction is `NEUTRAL`. This covers the range where the average sentiment falls between -0.15 and +0.15 without high contradiction — the evidence is either balanced or insufficient to establish a directional lean.
The mixed-first evaluation order is important. Consider a scenario where five documents are positive and four are negative, all with similar weights. The weighted sentiment average might be slightly positive (say, +0.08), which would normally map to neutral. But the contradiction score — computed from the minority/majority weight split — would be high (close to 0.44). The mixed rule catches this case: the evidence is not neutral, it is conflicted. This distinction matters downstream because mixed trends receive different treatment in the recommendation engine than neutral trends.
---
## Contradiction Detection
The contradiction detection module in `services/aggregation/contradiction.py` provides a structured analysis of disagreement within the signal set. Rather than collapsing contradictory evidence into a single number, it produces a `ContradictionResult` containing both an overall score and a list of `DisagreementDetail` objects that explain *where* the disagreement lies.
The `detect_contradictions()` function runs two analyses:
### Sentiment Disagreement
The `_detect_sentiment_disagreement()` function examines whether both positive and negative sentiment signals exist in the signal set. For each signal with a non-zero effective weight (`combined_weight × impact_score > 0`), it classifies the signal as positive or negative based on its `sentiment_value` and accumulates the effective weight for each side. If both sides have at least one signal, it produces a `DisagreementDetail` with dimension `"sentiment"`, listing the document IDs and weights for each side, along with a human-readable description like "Sentiment split: 3 positive vs 2 negative signals (minority weight ratio 38%)".
### Catalyst-Level Disagreement
The `_detect_catalyst_disagreement()` function goes deeper. It groups signals by their `catalyst_type` (performance_report, product_launch, regulatory, etc.) using `CatalystEntry` objects built from the `document_impact_records`. Within each catalyst group, it checks whether both positive and negative signals exist. If they do, it produces a `DisagreementDetail` with dimension `"catalyst:<type>"` — for example, `"catalyst:performance_report"` when some documents interpret a periodic disclosure positively and others negatively. This catalyst-level analysis is valuable because it pinpoints the specific topic of disagreement rather than just flagging that disagreement exists somewhere in the evidence.
### The Overall Contradiction Score
The `_compute_overall_score()` function computes the backward-compatible scalar contradiction score using the minority/majority weight ratio formula:
```
contradiction_score = minority_weight / total_weight
```
where `minority_weight` is the smaller of the positive and negative effective weights, and `total_weight` is their sum. Signals with zero effective weight or neutral sentiment are excluded. The score ranges from `0.0` (complete agreement — all signals point the same direction) to `0.5` (perfect split — positive and negative weights are exactly equal). A score of `0.0` means no contradiction at all. A score above `0.10` combined with a weak average sentiment triggers the mixed direction classification in `derive_trend_direction()`.
The contradiction score also feeds directly into the confidence computation as a penalty, described in the next section. High contradiction reduces the system's confidence in the trend, which in turn affects whether the trend can escalate to actionable recommendations.
---
## Evidence Ranking
Not all documents contributing to a trend are equally important. The `rank_evidence()` function in `services/aggregation/worker.py` delegates to the evidence ranking module (`services/aggregation/evidence.py`) to produce ordered lists of the most influential supporting and opposing documents. The ranking uses a composite scoring approach configured by `EvidenceRankConfig`, considering multiple factors:
- **Weight** — the signal's composite weight from the scoring layer, reflecting recency, credibility, novelty, confidence, and environmental context.
- **Impact** — the extraction's impact score for the entity, reflecting how significant the document's content is.
- **Recency** — how recently the document was published, with more recent documents ranked higher.
- **Confidence** — the extraction confidence, reflecting how reliably the LLM parsed the document.
Signals are split into supporting (positive sentiment) and opposing (negative sentiment) groups. Neutral and mixed sentiment signals are excluded from evidence lists — they do not argue for or against the trend direction. Within each group, signals are sorted by their composite rank score in descending order, and the top entries (up to `MAX_EVIDENCE_REFS = 10` per side) are returned as document ID lists.
The `assemble_trend_with_evidence()` function in `services/aggregation/worker.py` uses the detailed variant `rank_evidence_detailed()` to get `RankedEvidence` objects that include the individual scoring components (weight, impact, recency, confidence, sentiment value). These detailed rankings are persisted to the `trend_evidence` table for auditability, while the document ID lists are stored directly in the `TrendSummary` as `top_supporting_evidence` and `top_opposing_evidence`.
The evidence ranking serves two purposes. First, it provides the recommendation engine with the most relevant documents to cite in its thesis generation (see [Page 5](05-recommendation-generation.md)). Second, it gives human reviewers a quick way to understand *why* the system reached a particular trend assessment — the top-ranked documents are the ones that most influenced the direction and strength.
---
## Confidence Computation
The `compute_trend_confidence()` function in `services/aggregation/worker.py` produces the confidence score for a `TrendSummary`. This score is critical because it directly gates whether a trend can produce actionable recommendations — the eligibility evaluation in `services/recommendation/eligibility.py` requires a minimum confidence of `0.35` to generate any recommendation at all, and higher confidence thresholds control escalation to simulation and live execution modes.
Confidence is computed from four components:
### Unique Source Count
The function counts the number of unique document IDs across all active signals (those with `combined_weight > 0`). This count is divided by 15 and capped at `0.8`:
```
count_factor = min(unique_sources / 15.0, 0.8)
```
A trend backed by 15 or more unique source documents reaches the maximum count contribution of `0.8`. A trend backed by a single document gets only `0.067`. This component rewards breadth of evidence — a trend confirmed by many independent sources is more trustworthy than one driven by a single article, regardless of how high that article's individual weight might be.
### Average Extraction Credibility
The average credibility weight across all active signals provides a baseline quality measure. If most contributing documents come from high-credibility sources, this component is high. If the evidence is dominated by low-credibility sources, confidence is penalized accordingly.
### Signal Agreement with Sample-Size Dampening
The agreement ratio measures what fraction of directional signals (positive + negative, excluding neutral) agree on the majority direction. If 8 out of 10 directional signals are positive, the raw agreement is `0.8`. But raw agreement is misleading with small sample sizes — 1 out of 1 signals agreeing gives a perfect `1.0` agreement, which is not meaningful.
To address this, the agreement is dampened by a logarithmic sample-size factor:
```
agreement_dampener = min(1.0, log₂(unique_sources + 1) / log₂(8))
```
This dampener saturates at `1.0` when `unique_sources` reaches approximately 7 (since `log₂(8) = 3.0` and `log₂(8) = 3.0`). With fewer sources, the dampener reduces the agreement contribution: 1 source gives a dampener of `0.33`, 3 sources give `0.67`, and 7 sources give the full `1.0`. The log₂ scaling means that each additional source provides diminishing marginal improvement to the dampener, which matches the intuition that the jump from 1 to 3 sources is far more meaningful than the jump from 15 to 17.
### Contradiction Penalty
The contradiction score computed by `services/aggregation/contradiction.py` is applied as a direct penalty:
```
contradiction_penalty = contradiction_score × 0.4
```
A contradiction score of `0.5` (perfect split) produces a penalty of `0.2`, which is substantial enough to push a moderately confident trend below the eligibility threshold.
### The Combined Formula
The four components are combined as:
```
confidence = 0.3 × count_factor + 0.3 × avg_credibility + 0.4 × agreement contradiction_penalty
```
The result is clamped to `[0.0, 1.0]`. The weighting gives signal agreement the largest share (40%), reflecting the principle that consensus among diverse sources is the strongest indicator of a reliable trend. Source count and credibility each contribute 30%, providing a balanced assessment of evidence breadth and quality. The contradiction penalty can reduce confidence significantly — a highly contradicted trend with a score of 0.4 loses 0.16 points of confidence, which can easily drop it below the 0.35 eligibility gate.
---
## How Accumulating Signals Escalate Decisions
The trend direction, strength, and confidence computed by the aggregation engine are not just descriptive — they directly determine what action the system takes. The escalation path from passive observation to active execution is governed by the eligibility thresholds defined in `services/recommendation/eligibility.py`, and the key insight is that consecutive signals pointing in the same direction naturally strengthen the trend metrics that control this escalation.
### The Escalation Ladder
The `EligibilityConfig` dataclass in `services/recommendation/eligibility.py` defines the thresholds that map trend metrics to actions:
**Neutral (no recommendation).** A trend fails the eligibility gates entirely when confidence is below `0.35`, trend strength is below `0.10`, contradiction exceeds `0.60`, evidence count is below `2`, or the direction is neutral. The `_check_gates()` function evaluates these hard gates — if any gate fails, no recommendation is generated for that window.
**Observe.** A trend that passes the gates but has a direction of mixed, or has strength below `0.25` with confidence below `0.50`, maps to an `OBSERVE` action via `_determine_action()`. This is the system's way of saying "something is happening, but the evidence is not strong enough to act on." Observe recommendations are always `informational` mode — they are logged for human review but never trigger decisions.
**Monitor.** When the trend has a clear direction (positive or negative) but strength remains below `0.25` while confidence reaches `0.50` or above, the action maps to `MONITOR`. This indicates that the directional signal is real but not yet strong enough for a commitment change. Like observe, monitor recommendations are `informational` mode.
**Act / Defer.** When trend strength reaches `0.25` or above with a positive direction, the action is `ACT`. With a negative direction at the same strength threshold, the action is `DEFER`. These are the only actions that can escalate beyond informational mode — `_determine_mode()` evaluates whether the recommendation qualifies for `simulation_eligible` (confidence ≥ `0.50`) or `production_eligible` (confidence ≥ `0.70`, contradiction ≤ `0.25`, evidence ≥ `5`).
### How Accumulation Drives Escalation
Consider an entity that starts with no recent intelligence. The first negative article arrives — a single document with negative sentiment. In the intraday window, this produces:
- **Trend strength** = `|avg_sentiment|` ≈ the absolute weighted sentiment from one signal, likely close to the impact score.
- **Confidence** = low, because `count_factor = min(1/15, 0.8) = 0.067` and the agreement dampener is only `log₂(2)/log₂(8) = 0.33`.
- **Direction** = negative (if the weighted sentiment is ≤ -0.15).
With confidence well below `0.35`, this trend fails the eligibility gate entirely. No recommendation is generated. The system is in the neutral state.
A second negative article arrives hours later. Now the intraday window has two signals:
- **Unique sources** = 2, so `count_factor = 0.133` and `agreement_dampener = log₂(3)/log₂(8) ≈ 0.53`.
- **Agreement** = `1.0 × 0.53 = 0.53` (both signals agree on negative).
- **Confidence** ≈ `0.3 × 0.133 + 0.3 × avg_cred + 0.4 × 0.53` — likely around `0.35-0.45` depending on credibility.
If confidence crosses `0.35` and strength exceeds `0.10`, the trend passes the eligibility gates. But with strength below `0.25`, the action is `OBSERVE` or `MONITOR` depending on confidence.
A third and fourth negative article arrive over the next day. The 1-day window now has four agreeing signals:
- **Unique sources** = 4, so `count_factor = 0.267` and `agreement_dampener = log₂(5)/log₂(8) ≈ 0.77`.
- **Agreement** = `1.0 × 0.77 = 0.77`.
- **Confidence** ≈ `0.3 × 0.267 + 0.3 × avg_cred + 0.4 × 0.77` — likely `0.50-0.60`.
- **Strength** = `|avg_sentiment|` — with four negative signals and no contradicting evidence, this could easily exceed `0.25`.
Now the trend maps to `DEFER` with `simulation_eligible` mode (confidence ≥ `0.50`). The system has escalated from no recommendation to a simulation-eligible defer recommendation purely through the accumulation of consistent negative evidence.
If the negative evidence continues — more documents, more sources, higher credibility — confidence climbs further. At confidence ≥ `0.70` with contradiction ≤ `0.25` and evidence ≥ `5`, the recommendation reaches `production_eligible` mode, the highest escalation level.
The same process works in reverse for positive accumulation: consecutive favorable signals strengthen the positive trend, increase confidence through source diversity and agreement, and escalate from observe through monitor to act.
### The Role of Contradiction in Preventing False Escalation
Accumulation only works when signals agree. If the fifth article about an entity is positive while the previous four were negative, the contradiction score jumps — `minority_weight / total_weight` increases because the minority (positive) side now has non-zero weight. This has two effects: the contradiction penalty reduces confidence (potentially dropping it below an eligibility threshold), and if the contradiction exceeds `0.10` with `|avg_sentiment| < 0.30`, the direction flips to mixed, which maps to `OBSERVE` regardless of strength. The system effectively de-escalates when the evidence becomes contested, requiring a clearer consensus before re-escalating.
---
## Trend Projections
After the `TrendSummary` is assembled and persisted, the aggregation engine computes a forward-looking `TrendProjection` via `compute_projection()` in `services/aggregation/projection.py`. Projections estimate where the trend is heading based on current momentum, macro signal decay, and upcoming catalysts. They are advisory — they do not directly trigger recommendations — but they provide valuable context for human reviewers and can inform future automated decision-making.
### Momentum
The `compute_trend_momentum()` function computes the rate of change in signed trend strength between the current and previous aggregation cycles. If the current window shows a negative trend at strength `0.40` and the previous cycle showed negative at `0.30`, the momentum is `-0.10` (strengthening negative). If no previous data is available, the function uses a heuristic: momentum is estimated as half the current signed strength, providing a reasonable baseline for new trends.
Momentum enters the projection as a half-weighted adjustment to the current signed strength:
```
momentum_projected_signed = direction_sign × current_strength + momentum × 0.5
```
This means momentum influences the projection but does not dominate it — a strong current trend with weakening momentum still projects as directional, just with reduced strength.
### Macro Decay
The `project_macro_decay()` function estimates how active macro events will evolve over the projection horizon. Each macro event has an `estimated_duration` that maps to a decay half-life:
| Duration | Half-Life |
|----------|-----------|
| `short_term` | 1 day |
| `medium_term` | 7 days |
| `long_term` | 30 days |
For each event, the function computes the projected remaining impact at the end of the horizon using exponential decay: `future_factor = 2^(future_age_days / half_life)`. The impact is further scaled by a severity weight (`critical`: 1.0, `high`: 0.75, `moderate`: 0.5, `low`: 0.25). Positive and negative macro impacts are accumulated separately, and the projected macro direction is determined by comparing the two sides — positive if the favorable side exceeds the unfavorable by 20%, negative if the reverse, mixed if both are present without a clear majority.
When the macro layer is enabled and macro events exist, the projection blends the entity-specific momentum projection with the macro trajectory. The macro weight is capped at `0.4` (40% of the blended projection), ensuring that macro signals inform but do not overwhelm the entity-specific trend. The blending formula combines the signed entity projection with the signed macro projection:
```
blended = company_weight × momentum_projected + macro_weight × macro_signed
```
### Driving Factors
The projection records a list of human-readable driving factors that explain what is influencing the projected direction. These include momentum descriptions ("Positive momentum (+0.150) in recent trend strength"), macro impact projections ("Macro signals project negative impact (strength 0.350) over 7d"), and upcoming catalysts drawn from the trend's `dominant_catalysts` list (limited to the top 3). If no specific factors are identified, a baseline continuation factor is recorded.
### Divergence Detection
After computing the projected direction, the function compares it to the current trend direction. If they differ — for example, the current trend is negative but the projection is positive due to decaying unfavorable macro events and favorable momentum — the projection is flagged with `diverges_from_current = True` and a divergence driving factor is appended. Divergence signals are particularly valuable because they indicate that the trend may be about to reverse, giving the recommendation engine and human reviewers an early warning.
The projection also flags low confidence when `projected_confidence` falls below the default threshold of `0.3`. Projection confidence starts at 80% of the current trend confidence (reflecting the inherent uncertainty of forward-looking estimates), with a small boost if macro data is available and a further reduction if the macro layer is disabled entirely.
---
## Persistence
Each aggregation cycle persists its results to four PostgreSQL tables, creating a durable record of the trend assessment and its supporting evidence.
### `trend_windows` — Current State
The `persist_trend_summary()` function in `services/aggregation/worker.py` upserts the `TrendSummary` into the `trend_windows` table, keyed by `(entity_type, entity_id, window)`. Each cycle overwrites the previous row for that entity and window, so `trend_windows` always reflects the most recent assessment. The row includes the trend direction, strength, confidence, contradiction score, disagreement details (as JSON), supporting and opposing evidence document IDs (as JSON arrays), dominant catalysts, material risks, environmental context, and the generation timestamp.
### `trend_history` — Time-Series Snapshots
Immediately after the upsert, `persist_trend_summary()` also inserts a snapshot row into the `trend_history` table. Unlike `trend_windows`, this table is append-only — every aggregation cycle adds a new row, creating a time-series of how the trend evolved over time. The history table stores the direction, strength, confidence, contradiction score, catalysts, risks, and timestamp. This time-series data powers the trend charts in the dashboard and enables the momentum computation in `services/aggregation/projection.py` by providing the previous cycle's strength and direction. If the history insert fails (for example, if the table does not yet exist in a development environment), the failure is logged at debug level and does not block the main upsert.
### `trend_evidence` — Per-Document Rankings
The `persist_trend_evidence()` function writes detailed evidence ranking rows to the `trend_evidence` table, linked to the `trend_windows` row by its UUID. Each row records a document ID, its role (supporting or opposing), and the individual scoring components: rank score, weight component, impact component, recency component, confidence component, and sentiment value. Non-UUID document IDs (such as synthetic pattern signal IDs like `pattern:Entity-A:performance_report:7d`) are filtered out before insertion, since the `trend_evidence` table enforces a foreign key to the `documents` table.
### `trend_projections` — Forward-Looking Estimates
The `persist_trend_projection()` function in `services/aggregation/projection.py` inserts the `TrendProjection` into the `trend_projections` table, linked to the `trend_windows` row. The row stores the projected direction, strength, confidence, projection horizon, driving factors (as JSON), macro contribution percentage, divergence flag, and computation timestamp. Like trend history, projections accumulate over time, allowing analysis of how well the system's forward-looking estimates matched subsequent reality.
---
## What Comes Next
At this point, the aggregation engine has transformed weighted signals into `TrendSummary` objects across five time windows, detected contradictions, ranked evidence, computed confidence, and persisted everything to PostgreSQL. The trend metrics — direction, strength, confidence, contradiction score — encode the accumulated weight of evidence for each entity. But a `TrendSummary` is still an assessment, not an action. The next stage translates these assessments into concrete recommendations: should the system act, defer, monitor, or simply observe? And with what conviction? [Page 5 — Recommendation Generation](05-recommendation-generation.md) explains how the recommendation engine applies data quality suppression, eligibility evaluation, commitment sizing, thesis generation, and risk classification to convert trend summaries into actionable `Recommendation` objects that the decision execution engine can execute.
@@ -0,0 +1,226 @@
# Page 5 — Recommendation Generation and Signal-to-Action Translation
The aggregation engine described in [Page 4](04-trend-aggregation-and-accumulating-signals.md) produces `TrendSummary` objects across five time windows for each entity identifier, encoding the direction, strength, confidence, contradiction level, and supporting evidence accumulated from all three signal layers. But a `TrendSummary` is an assessment — it describes what the evidence says, not what the system should do about it. The recommendation engine is where assessment becomes action. It takes each `TrendSummary`, subjects it to a series of deterministic evaluations, and produces a `Recommendation` object that specifies a concrete action (act, defer, monitor, or observe), an execution mode (informational, simulation-eligible, or production-eligible), a commitment sizing guideline, a human-readable thesis, and a risk classification. Every decision in this pipeline is rule-based and fully traceable — the LLM is only involved in an optional downstream step that rewrites the thesis wording.
The recommendation worker in `services/recommendation/main.py` polls the `app:queue:recommendation` Redis queue for jobs, each specifying an entity identifier and time window. For each job, it delegates to `generate_recommendation()` in `services/recommendation/worker.py`, which orchestrates the full pipeline: fetch the latest trend summary, check for duplicate recommendations, fetch any available trend projection, evaluate data quality suppression, evaluate eligibility, optionally rewrite the thesis via LLM, build the `Recommendation` object, and persist everything to PostgreSQL. For a visual overview of this flow, see the [Recommendation Generation Flow diagram](diagrams/recommendation-generation-flow.md).
---
## Data Quality Suppression
Before the eligibility engine evaluates whether a trend is strong enough to act on, the suppression layer in `services/recommendation/suppression.py` asks a more fundamental question: is the underlying data reliable enough to act on at all? A trend might show high confidence and strong directionality, but if the documents feeding it are stale, poorly extracted, or drawn from a single source type, the apparent signal quality is illusory. The suppression layer acts as a pre-filter on data quality, running before the eligibility engine and forcing any recommendation built on unreliable data to `informational` mode regardless of how strong the trend metrics look.
The `evaluate_suppression()` function accepts a `TrendSummary` and a `DataQualityContext` — a set of metrics about the documents underlying the trend, populated by querying `documents` and `document_intelligence` tables for the evidence document IDs stored in the trend summary. When full document-level metrics are not available (for example, in a development environment without the full document pipeline), the function falls back to `build_quality_context_from_summary()`, which estimates quality metrics from the trend summary's own evidence counts and confidence.
### The Six Data Quality Checks
The suppression evaluation runs six independent checks, each comparing a data quality metric against a configurable threshold defined in `SuppressionConfig`. If any single check fails, the recommendation is suppressed:
1. **Low extraction confidence** — If the average extraction confidence across the evidence documents falls below `0.40` (`min_avg_extraction_confidence`), the underlying LLM extractions are too unreliable. This catches cases where the extractor struggled with document formatting, ambiguous content, or low-quality source material, as described in [Page 2](02-ai-agent-processing-and-extraction.md).
2. **Evidence staleness** — If the most recent evidence document is older than `168` hours (7 days, `max_evidence_staleness_hours`), the trend is based on outdated information. Conditions change rapidly, and a week-old evidence base may no longer reflect the current state. When documents exist but no timestamp is available, the evidence is conservatively treated as stale.
3. **Low source diversity** — If fewer than `1` distinct source type (`min_source_types`) contributed to the evidence, the signal may be driven by a single unreliable source class. In practice, this check fires when the quality context has documents but all come from the same source type (for example, all news articles with no filings or supplementary data to corroborate).
4. **High extraction failure rate** — If more than `50%` (`max_extraction_failure_rate`) of the documents that should have contributed to the trend failed extraction entirely, the data pipeline is unreliable for this entity. A high failure rate means the trend summary is built from a biased subset of the available evidence — the failed documents might have told a different story.
5. **Insufficient valid documents** — If fewer than `2` valid (non-failed) documents (`min_valid_documents`) contributed to the trend, there simply is not enough data to act on. A single document, no matter how high-quality, does not provide the corroboration needed for automated execution decisions.
6. **Low data quality score** — The `_compute_data_quality_score()` function computes an overall quality score from three weighted components: extraction confidence (40% weight, normalized against a 0.8 baseline), evidence freshness (30% weight, linear decay over the staleness window), and document coverage (30% weight, combining the valid/total ratio with a count factor that saturates at 10 documents). If this composite score falls below `0.30` (`min_data_quality_score`) and the low-confidence check has not already fired, a general suppression reason is added.
When any check triggers, the `SuppressionResult` records the specific reasons (as `SuppressionReason` enum values) and the computed data quality score. The worker in `services/recommendation/worker.py` uses this result to force the recommendation's mode to `informational` and append a suppression note to the thesis text, ensuring the suppression decision is visible in the audit trail.
### Safety Suppressions: Macro-Only and Pattern-Only Signals
Beyond the six data quality checks, two additional safety suppressions protect against acting on signals that lack entity-specific corroboration:
**Macro-only suppression** (`evaluate_macro_only_suppression()`) fires when macro signals are the sole basis for a trend direction — no entity-specific signals contributed at all. As described in [Page 3](03-signal-scoring-and-weighted-signals.md), macro signals enter the aggregation engine at a reduced weight of `0.3` relative to entity-specific signals. But even at reduced weight, macro signals alone can shift a trend direction if no entity-specific evidence exists. When this happens, the recommendation is forced to `informational` mode with a caveat noting that the signal is macro-only and should not be used for automated execution.
**Pattern-only suppression** (`evaluate_pattern_only_suppression()`) applies the same logic to competitive/pattern signals. When pattern-based signals from `services/aggregation/pattern_matcher.py` and `services/aggregation/signal_propagation.py` are the sole contributors — no entity-specific or macro signals — the recommendation is suppressed. Historical patterns are valuable context, but acting on them without any current evidence is too speculative for automated execution.
Both safety suppressions are evaluated in the worker after the main suppression check, and both force the mode to `informational` when triggered.
---
## Eligibility Evaluation
Recommendations that survive the suppression layer enter the eligibility evaluation in `services/recommendation/eligibility.py`. This is the core decision logic — a set of deterministic rules that map trend metrics to actions, execution modes, and commitment sizing. The `evaluate_eligibility()` function is the single entry point, accepting a `TrendSummary` and an `EligibilityConfig` of tunable thresholds.
### Gate Checks
The `_check_gates()` function applies five hard gates. If any gate fails, the trend is ineligible for a recommendation (though the action and mode are still computed for the audit trace):
| Gate | Threshold | Rejection Reason |
|------|-----------|-----------------|
| Confidence | ≥ `0.35` | `low_confidence` |
| Trend strength | ≥ `0.10` | `low_trend_strength` |
| Contradiction score | ≤ `0.60` | `high_contradiction` |
| Evidence count | ≥ `2` (supporting + opposing) | `insufficient_evidence` |
| Direction | ≠ `neutral` | `neutral_direction` |
These gates are intentionally conservative. A confidence threshold of `0.35` means the system needs meaningful evidence breadth and agreement before generating any recommendation at all (see the confidence computation in [Page 4](04-trend-aggregation-and-accumulating-signals.md)). The contradiction ceiling of `0.60` allows moderately contested trends through — only when the evidence is deeply split does the gate reject. The evidence minimum of `2` ensures that no recommendation is ever based on a single document.
When a trend fails any gate, the resulting `EligibilityResult` has `eligible = False` and the mode is forced to `informational`, regardless of what the mode escalation logic would otherwise compute.
### Action Mapping
The `_determine_action()` function maps the trend's direction and strength to one of four action types. The logic evaluates in a specific order:
**Mixed or neutral direction → OBSERVE.** If the trend direction is `mixed` (high contradiction with weak directional signal) or `neutral`, the action is always `OBSERVE`. There is no directional conviction to act on.
**Strong directional signal → ACT or DEFER.** If the trend strength reaches `0.25` or above (`action_strength_threshold`), the action follows the direction: `ACT` for positive, `DEFER` for negative. This threshold ensures that only trends with meaningful magnitude trigger commitment-changing actions.
**Weak directional signal with decent confidence → MONITOR.** If the trend has a clear direction (positive or negative) but strength remains below `0.25`, the action depends on confidence. If confidence reaches `0.50` or above (`hold_confidence_threshold`), the action is `MONITOR` — the system recognizes the directional lean but does not have enough conviction to recommend a commitment change. Below `0.50` confidence, the action falls to `OBSERVE`.
This mapping creates the escalation ladder described in [Page 4](04-trend-aggregation-and-accumulating-signals.md): as consecutive signals accumulate and strengthen the trend metrics, the action naturally progresses from OBSERVE → MONITOR → ACT/DEFER.
### Mode Escalation
The `_determine_mode()` function determines the highest execution mode allowed for the recommendation. Mode controls whether the recommendation is purely informational, eligible for simulation mode, or eligible for live execution mode:
**OBSERVE and MONITOR → always informational.** These actions do not trigger executions, so they are always `informational` mode. They are logged for human review and dashboard display but never enter the decision execution engine.
**ACT and DEFER → escalation based on signal quality.** For actionable recommendations, mode escalates through three tiers:
- **`informational`** — The default when confidence is below `0.50`. The recommendation is recorded but not eligible for any execution.
- **`simulation_eligible`** — When confidence reaches `0.50` or above (`paper_confidence_threshold`). The recommendation can be picked up by the simulation engine described in [Page 6](06-decision-execution.md).
- **`production_eligible`** — The strictest tier, requiring confidence ≥ `0.70` (`live_confidence_threshold`), contradiction ≤ `0.25` (`live_max_contradiction`), and evidence count ≥ `5` (`live_min_evidence`). This triple gate ensures that only high-conviction, well-corroborated, low-contradiction recommendations can trigger live executions.
The evidence count for mode escalation is computed as the sum of supporting and opposing evidence documents, matching the same count used in the gate checks.
---
## Commitment Sizing
The `_compute_position_sizing()` function in `services/recommendation/eligibility.py` translates signal quality into an allocation pool guideline. Commitment sizing is not a fixed value — it scales dynamically with the confidence and strength of the underlying trend, penalized by contradiction and thin evidence.
### Base and Scaling
The computation starts with a base allocation of `1%` (`base_allocation_pct = 0.01`) and scales upward based on two factors:
- **Confidence factor** — `0.8 × confidence` (`confidence_sizing_weight`), reflecting how much the system trusts the trend assessment.
- **Strength factor** — `0.5 + 0.5 × trend_strength`, ranging from `0.5` (weakest trend) to `1.0` (strongest trend).
The raw allocation percentage is computed as:
```
raw_allocation = base + confidence_factor × strength_factor × (max - base)
```
where `max` is `10%` (`max_allocation_pct = 0.10`). At maximum confidence (1.0) and maximum strength (1.0), the raw allocation reaches the full 10%. At typical values (confidence 0.6, strength 0.3), the raw allocation is considerably lower.
### Contradiction Penalty
The contradiction score applies a multiplicative penalty:
```
allocation_pct = raw_allocation × (1.0 0.5 × contradiction_score)
```
A contradiction score of `0.40` reduces the allocation by 20%. A score of `0.0` (no contradiction) applies no penalty. This ensures that contested trends receive smaller commitment sizes even when they pass the eligibility gates.
### Evidence Count Penalty
Thin evidence further reduces the allocation:
- Fewer than `3` evidence documents → multiply by `0.5` (halved).
- Fewer than `5` evidence documents → multiply by `0.75`.
- `5` or more documents → no penalty.
This penalty stacks with the contradiction penalty, so a trend with high contradiction and thin evidence receives a substantially reduced commitment size.
### Max Loss Scaling
The same scaling logic applies to the maximum loss percentage, which starts at a base of `0.3%` (`base_max_loss_pct = 0.003`) and scales up to `2%` (`max_max_loss_pct = 0.02`). Higher-conviction commitments are allowed larger loss tolerances, while low-conviction or contested commitments are constrained to tighter risk thresholds.
The final `PositionSizing` object (defined in `services/shared/schemas.py`) contains `allocation_pct` and `max_loss_pct`, both clamped to their respective bounds. This object is embedded in the `Recommendation` and later consumed by the decision execution engine's own commitment sizer (described in [Page 6](06-decision-execution.md)), which applies additional resource pool-level constraints.
---
## Thesis Generation
Every recommendation includes a human-readable thesis that explains the reasoning behind the action. Thesis generation happens in two layers: a deterministic assembly that is always present, and an optional LLM rewrite that polishes the wording for execution-eligible recommendations.
### Deterministic Thesis Assembly
The `build_thesis()` function in `services/recommendation/worker.py` constructs a thesis string entirely from the trend data and eligibility result, with no model involvement. The thesis is assembled from several components in order:
1. **Opening** — States the entity identifier, trend direction, window, strength, and confidence. For example: "Entity-A shows a negative trend over the 7d window with strength 0.35 and confidence 0.62."
2. **Catalysts** — Lists the top three dominant catalysts from the `TrendSummary`, drawn from the evidence ranking described in [Page 4](04-trend-aggregation-and-accumulating-signals.md).
3. **Contradiction note** — If the contradiction score exceeds `0.15`, a note flags the signal disagreement and its magnitude.
4. **Trend projection** — When a `TrendProjection` is available and not flagged as low-confidence, the thesis incorporates the projected direction, strength, and top driving factors. If the projection diverges from the current trend, a divergence note is appended.
5. **Risks** — Lists the top two material risks from the `TrendSummary`.
6. **Evidence count** — States the number of supporting and opposing evidence documents.
7. **Prescriptive action** — States the recommended action and mode (e.g., "Recommendation: DEFER (simulation eligible).").
The deterministic thesis is always generated and serves as the audit reference. Even when the LLM rewrites the thesis, the deterministic version is preserved in the model metadata for traceability.
### Optional LLM Rewrite via the Thesis-Rewriter Agent
For recommendations that are both eligible and not suppressed, the worker optionally invokes the thesis-rewriter agent to polish the deterministic thesis into professional-quality prose. The LLM rewrite is implemented in `services/recommendation/thesis_llm.py` and uses the `thesis-rewriter` agent slug, resolved at runtime through the `AgentConfigResolver` in `services/shared/agent_config.py`.
The `AgentConfigResolver` queries the `ai_agents` and `agent_variants` database tables to resolve the active configuration for the `thesis-rewriter` slug, preferring an active variant's model, timeout, and retry settings when one exists. The resolver uses a 60-second TTL in-memory cache to avoid hitting the database on every recommendation. This is the same resolution mechanism used by the document extractor and event classifier agents described in [Page 2](02-ai-agent-processing-and-extraction.md).
The `rewrite_thesis_with_llm()` function builds a prompt from the deterministic thesis and trend context (entity identifier, window, direction, strength, confidence, contradiction score, catalysts, risks), sends it to the local Ollama instance via HTTP, and returns the rewritten text. The system prompt enforces strict rules: no fabricated information, no numbers or facts not present in the input, under 150 words, neutral professional tone, and only the rewritten thesis text in the response.
The LLM layer is purely additive — if the call fails for any reason (network error, timeout, empty response, token budget exceeded), the original deterministic thesis is returned unchanged. The worker in `services/recommendation/main.py` resolves the thesis-rewriter configuration at startup and refreshes it every 50 jobs to pick up configuration changes without requiring a restart. When no database configuration exists for the `thesis-rewriter` slug, thesis rewriting is silently disabled.
Performance logging for the thesis-rewriter is written to the `agent_performance_log` table, recording success/failure, duration, estimated token counts, and the variant ID. Token budget enforcement checks hourly usage against the variant's configured budget before making the LLM call, preventing runaway costs from high-volume recommendation cycles.
### Risk Classification Prefix
Before the thesis is stored, the `classify_risk()` function in `services/recommendation/worker.py` assigns a risk classification label that is prepended to the thesis text as a `[risk:<level>]` prefix. The classification is computed from a composite score:
| Factor | Contribution |
|--------|-------------|
| Contradiction score | `contradiction × 2.0` |
| Low confidence | `(1.0 confidence) × 1.5` |
| Low evidence count | `+1.0` if < 3 docs, `+0.5` if < 5 docs |
| Rejection reasons | `+0.5` per rejection reason |
The composite score maps to four levels:
| Score Range | Classification |
|-------------|---------------|
| ≥ 3.0 | `very_high` |
| ≥ 2.0 | `high` |
| ≥ 1.0 | `moderate` |
| < 1.0 | `low` |
A recommendation with high contradiction (0.4 → contributes 0.8), moderate confidence (0.55 → contributes 0.675), and 4 evidence documents (contributes 0.5) would score 1.975, classifying as `moderate`. The same recommendation with only 2 evidence documents would score 2.475, pushing it to `high`. This classification gives downstream consumers — both the decision execution engine and human reviewers — a quick risk signal without needing to re-evaluate the underlying metrics.
---
## Persistence
The recommendation pipeline persists its output to three PostgreSQL tables, creating a complete audit trail from trend assessment through decision logic to the final recommendation.
### `recommendations` — The Core Record
The `persist_recommendation()` function in `services/recommendation/worker.py` inserts the `Recommendation` into the `recommendations` table. Each row captures the entity identifier, action, mode, confidence, time horizon, thesis (including the risk classification prefix and any suppression notes), invalidation conditions (as JSONB), commitment sizing (allocation percentage and max loss percentage), model metadata (provider, model name, prompt version, schema version), risk classification, and generation timestamp. The insert returns the recommendation's UUID, which serves as the foreign key for the evidence and risk evaluation tables.
### `recommendation_evidence` — Evidence Citations
For each evidence document referenced in the recommendation, a row is inserted into the `recommendation_evidence` table linking the recommendation UUID to the document UUID, with an evidence type (`supporting` or `opposing`) and a position-based weight that decays with rank: `weight = 1.0 / (1.0 + index × 0.1)`. The first supporting document gets weight `1.0`, the second gets `0.91`, the third `0.83`, and so on. Non-UUID document IDs (such as synthetic pattern signal IDs like `pattern:Entity-A:performance_report:7d` from the competitive signal layer) are filtered out before insertion, since the table enforces a foreign key to the `documents` table.
### `risk_evaluations` — Decision Audit Trail
The `risk_evaluations` table records the full eligibility decision for each recommendation: whether the trend was eligible, the allowed mode, the list of rejection reasons (as JSONB), and a `risk_checks` JSONB object containing the time horizon, commitment sizing details, invalidation conditions, and risk classification. This table enables post-hoc analysis of why the system made a particular decision — auditors can trace from the recommendation back through the eligibility evaluation to the underlying trend metrics.
---
## Deduplication
Before running the full evaluation pipeline, the worker checks whether the latest recommendation for the same entity identifier and time horizon is effectively identical to what would be generated. The `_is_duplicate_recommendation()` function in `services/recommendation/worker.py` compares the previous recommendation's action, mode, and confidence (within a `0.01` tolerance) against the current eligibility result. If all three match, the recommendation is skipped — the underlying trend data has not changed meaningfully since the last cycle. This prevents the system from flooding the `recommendations` table with identical entries on every aggregation cycle, while still generating a new recommendation whenever the trend metrics shift enough to change the action, mode, or confidence.
---
## What Comes Next
At this point, the recommendation engine has translated trend assessments into concrete `Recommendation` objects — each with an action, execution mode, commitment sizing guideline, thesis, and risk classification — and persisted them alongside their evidence citations and eligibility audit trails. Recommendations marked as `simulation_eligible` or `production_eligible` are now available for the decision execution engine to consume. [Page 6 — Decision Execution](06-decision-execution.md) explains how the decision execution engine polls these recommendations, applies its own pre-execution check sequence (circuit breakers, execution windows, confidence gates, deduplication, declining commitments, and max open commitments), computes final commitment sizes with resource pool-level constraints, and submits execution requests through the execution adapter to the external execution API.
@@ -0,0 +1,199 @@
# Page 6 — Decision Execution
The recommendation engine described in [Page 5](05-recommendation-generation.md) produces `Recommendation` objects with an action, execution mode, commitment sizing guideline, thesis, and risk classification. Recommendations marked as `simulation_eligible` or `production_eligible` are persisted to the `recommendations` table and are now available for the final stage of the pipeline: autonomous decision execution. The decision execution engine in `services/trading/engine.py` is where intelligence becomes action. It polls eligible recommendations, subjects each one to a strict sequence of pre-execution safety checks, computes a pool-aware commitment size, and — if every gate passes — submits an execution request through the execution adapter to the external execution API. Every evaluation, whether it results in a decision or a skip, is recorded as a `DecisionRecord` in the `execution_decisions` table, creating a complete audit trail from the original document signal through to the execution response.
For a visual overview of the decision flow, see the [Decision Engine Loop diagram](diagrams/decision-engine-loop.md).
---
## The Decision Execution Engine Loop
The `DecisionEngine` class in `services/trading/engine.py` is the orchestrator. When `start()` is called, it loads the current resource pool state from PostgreSQL — active commitments, reserve pool balance, sector exposure, pool exposure — and then spawns five concurrent `asyncio` tasks that run for the lifetime of the engine:
1. **`_decision_loop()`** — The core polling loop. Every 60 seconds (configurable via `polling_interval_seconds`), it queries the `recommendations` table for rows where `action IN ('act', 'defer')`, `mode IN ('simulation_eligible', 'production_eligible')`, and `generated_at` is within the last two hours. Recommendations are ordered by confidence descending and capped at 50 per cycle. For each recommendation, the engine fetches the current data point (first from `market_snapshots`, falling back to the data source API), then runs the full pre-execution evaluation pipeline described below.
2. **`_risk_threshold_monitor()`** — Periodically checks current values against the risk threshold and gain target levels maintained by the `RiskThresholdManager` in `services/trading/stop_loss_manager.py`. When a value crosses a risk threshold or gain target, the monitor submits a defer execution request to the execution queue. The `RiskThresholdManager` computes initial levels from ATR and risk tier parameters, re-evaluates them when volatility shifts materially (ATR change > 10%), activates trailing thresholds when the value moves more than 50% toward the gain target, and tightens thresholds proactively when pool exposure exceeds 80% of the maximum.
3. **`_performance_loop()`** — Computes pool-wide performance metrics (total value, unrealized and realized gain/loss, success rate, risk-adjusted return ratio, peak-to-trough decline, pool exposure), persists daily snapshots to `pool_snapshots`, checks for daily-loss circuit breaker triggers, evaluates gain-taking opportunities, and synchronizes commitments with the database to detect closed commitments and trigger reserve pool siphoning.
4. **`_risk_tier_scheduler()`** — Runs once daily at 16:00 ET (session close). It loads the latest `PerformanceMetrics` from `pool_snapshots`, computes the reserve pool as a fraction of total resource pool value, and delegates to the `RiskTierController` in `services/trading/risk_tier_controller.py` to determine whether the active risk tier should change. Tier changes are persisted to `risk_tier_history` and take effect immediately for subsequent decision cycles.
5. **`_rebalance_scheduler()`** — Runs weekly on Monday at 09:45 ET (shortly after session open). It loads current commitments, evaluates them against the active risk tier's constraints using the `PoolRebalancer`, and pushes any rebalance defer execution requests to `app:queue:execution_orders`. The rebalancer respects the circuit breaker — if any breaker is active, the rebalance cycle is skipped entirely.
All five tasks run concurrently within a single `asyncio` event loop. Graceful shutdown via `stop()` cancels all tasks and awaits their completion. If any task encounters an unexpected exception, it logs the error and retries after a brief sleep rather than crashing the engine.
---
## Pre-Execution Check Sequence
When the decision loop picks up an act recommendation, it calls `evaluate_recommendation()` — a synchronous method that runs the full pre-execution check sequence. The checks are applied in a strict order, and the first failure short-circuits the evaluation with a `skip` decision. This fail-fast design ensures that expensive downstream computations (like commitment sizing and correlation analysis) are never reached when a simple gate would have rejected the decision.
The six checks, in order:
**a. Circuit breaker check.** The engine calls `self.circuit_breaker.is_active()` on the current `CircuitBreakerState`. If any circuit breaker is active and its cooldown has not expired, the recommendation is skipped with reason `circuit_breaker_active`. The circuit breaker mechanism is described in detail below.
**b. Execution window check.** The `is_within_execution_window()` function verifies that the current time falls within the active session hours. Outside the execution window, no execution requests are submitted — the recommendation is skipped with reason `outside_execution_window`.
**c. Confidence gate.** The recommendation's confidence score is compared against the active risk tier's `min_confidence` threshold. A conservative tier requires confidence ≥ 0.75, moderate requires ≥ 0.55, and aggressive requires ≥ 0.40. If the recommendation's confidence falls below the tier minimum, it is skipped with reason `insufficient_confidence`. This gate ensures that the risk tier's conservatism is enforced before any resource allocation is considered.
**d. Deduplication check.** The engine maintains an in-memory set of processed recommendation IDs (`processed_recommendation_ids`) and also checks Redis via `app:dedupe:execution:*` keys (with a 24-hour TTL). If the recommendation has already been evaluated in this engine session or by a previous instance, it is skipped with reason `duplicate_recommendation`. This prevents the same recommendation from generating multiple execution requests across polling cycles.
**e. Declining commitments check.** The `check_declining_commitments()` method examines all active commitments. If more than 50% of commitments have unrealized losses exceeding 2% of their entry value, the engine halts new entries with reason `multiple_declining_commitments`. This is a pool-level safety valve — when the majority of existing commitments are underwater, adding new exposure compounds the risk.
**f. Max active commitments check.** The engine enforces a configurable maximum number of concurrent commitments (default 10). If the resource pool is already at capacity, the recommendation is skipped with reason `max_commitments_reached`.
For defer recommendations, the engine follows a separate, simpler path: it verifies the execution window, looks up the existing commitment for the entity, and submits a full-quantity defer execution request without running the commitment sizer. Defer decisions still generate an audit record in `execution_decisions` and set the Redis deduplication key.
If all six checks pass for an act recommendation, the engine proceeds to commitment sizing.
---
## Commitment Sizing
The `CommitmentSizer` in `services/trading/position_sizer.py` translates a recommendation's signal quality into a concrete dollar amount and unit count, applying a sequential pipeline of adjustments that account for confidence, pool composition, sector concentration, correlation, and upcoming performance report events. The sizer operates on the *active pool* — the portion of the resource pool available for execution after subtracting the reserve pool balance.
### Base Sizing
The computation begins with a base allocation percentage derived from the risk tier:
```
base_allocation_pct = risk_tier.max_position_pct × 0.5
raw_pct = base_allocation_pct × (confidence / min_confidence)
```
The base starts at half the tier's maximum commitment percentage, then scales linearly with how far the recommendation's confidence exceeds the tier minimum. A moderate-tier recommendation with confidence 0.70 against a minimum of 0.55 would produce a raw percentage of `0.05 × (0.70 / 0.55) ≈ 0.0636`, or about 6.4% of the active pool. The raw percentage is clamped to `max_position_pct` (5% for conservative, 10% for moderate, 15% for aggressive) and then converted to a dollar amount against the active pool. An absolute commitment cap (default $50) provides a hard ceiling regardless of pool size — a safety measure for the simulation mode environment.
### Correlation-Aware Diversification
The sizer computes a weighted average correlation between the candidate entity and all existing commitments, using the pairwise correlation matrix that the engine refreshes from 30 days of daily close values in `market_snapshots`. Each existing commitment's correlation is weighted by its value, so larger commitments have more influence on the diversification check.
If the weighted average correlation exceeds 0.8, the commitment is rejected outright — the resource pool already has too much exposure to correlated assets. Between 0.5 and 0.8, the dollar amount is reduced proportionally: a correlation of 0.65 produces a scale factor of `1.0 (0.65 0.5) / (0.8 0.5) = 0.5`, halving the commitment size. Below 0.5, no reduction is applied.
### Sector Exposure Reduction
The sizer checks whether adding the new commitment would push the sector's total exposure beyond the risk tier's `max_sector_pct` (20% for conservative, 30% for moderate, 40% for aggressive). If the sector is already at its limit, the commitment is rejected. If the new commitment would exceed the limit, the dollar amount is reduced to exactly fill the remaining sector capacity.
### Diversification Bonus
When the resource pool holds fewer than three distinct sectors and the candidate entity belongs to a new sector, the sizer applies a 1.2× bonus to the dollar amount. This incentivizes early diversification — the first few commitments are encouraged to spread across sectors rather than concentrating in a single one. The bonus is re-clamped to `max_position_pct` after application to prevent oversized commitments.
### Performance Report Proximity Adjustment
The sizer checks the performance report calendar for the candidate entity. If a performance report is within one active session, the commitment is rejected entirely — the binary risk of a disclosure surprise is too high for automated entry. If a performance report is within three active sessions, the dollar amount is reduced by 50%. Beyond three sessions, no adjustment is applied.
### Pool Exposure Check and Unit Rounding
After all adjustments, the sizer estimates the new commitment's contribution to pool exposure (the aggregate risk from risk threshold distances across all commitments). If adding the commitment would push total exposure beyond `max_portfolio_heat × active_pool` (10% for conservative, 20% for moderate, 30% for aggressive), the commitment is rejected.
Finally, the dollar amount is converted to whole units via `floor(dollar_amount / current_value)`. If rounding produces zero units (the commitment is too small for even one unit at the current value), the commitment is rejected. The final dollar amount is recalculated from the whole-unit quantity to reflect the actual capital deployed.
The `CommitmentSizeResult` returned to the engine includes the dollar amount, unit quantity, allocation percentage, a list of human-readable adjustment notes, and a rejected flag with reason if any step failed. These adjustment notes are embedded in the decision record's `decision_trace` for full auditability.
---
## Circuit Breaker
The `CircuitBreaker` in `services/trading/circuit_breaker.py` is a pure computation module that evaluates three independent trigger conditions. It carries no state of its own — the engine manages the `CircuitBreakerState` dataclass and persists trigger events to the `circuit_breaker_events` table and Redis keys under `app:execution:circuit_breaker:*`.
### Three Trigger Types
**Daily loss trigger.** When the resource pool's daily gain/loss exceeds 5% of total resource pool value (`daily_loss_pct = 0.05`), the circuit breaker activates. The `check_daily_loss()` method compares the absolute loss ratio against the threshold. The cooldown duration is set to `volatility_pause_hours` (default 2 hours). The performance loop in the engine calls `_check_circuit_breaker_daily_loss()` periodically to evaluate this condition against the latest pool metrics. In extreme cases where the peak-to-trough decline exceeds an emergency threshold, the reserve pool's emergency liquidation mechanism may also be triggered.
**Single commitment loss trigger.** When any individual commitment loses more than 15% of its entry value (`single_position_loss_pct = 0.15`), the circuit breaker activates with an entity-specific cooldown. The `check_single_position()` method evaluates the loss percentage. The cooldown for the affected entity is set to `ticker_cooldown_hours` (default 48 hours), during which the engine will not re-enter that entity. The `is_ticker_cooled_down()` method checks whether a specific entity is still within its cooldown window by consulting the `ticker_cooldowns` dictionary in the `CircuitBreakerState`.
**Volatility trigger (risk threshold clustering).** When three or more risk thresholds fire within a 30-minute rolling window (`stop_loss_hits_threshold = 3`, `stop_loss_window_minutes = 30`), the circuit breaker activates. The `check_volatility()` method uses a sliding window algorithm: it sorts the risk threshold timestamps and checks every contiguous subsequence of length `stop_loss_hits_threshold` to see if it fits within the window. This detects rapid-fire risk threshold cascades that indicate extreme volatility. The cooldown is `volatility_pause_hours` (default 2 hours).
### Cooldown Computation
The `compute_cooldown_expiry()` method calculates when a triggered breaker expires. For `daily_loss` and `volatility` triggers, the expiry is `triggered_at + volatility_pause_hours`. For `single_position` triggers, the expiry is `triggered_at + ticker_cooldown_hours`, giving the affected entity a longer cooling-off period. The `is_active()` method returns `True` when the breaker is flagged active and the current time has not yet passed the cooldown expiry.
### Redis State Tracking
The engine persists circuit breaker state to Redis under the `app:execution:circuit_breaker:*` key pattern (constructed by `execution_cb_key()` in `services/shared/redis_keys.py`). Each trigger type gets its own key — for example, `app:execution:circuit_breaker:daily_loss` — storing the activation timestamp and cooldown expiry. This allows the state to survive engine restarts and enables external monitoring tools to query breaker status without accessing the engine's memory.
---
## Reserve Pool
The `ReservePoolController` in `services/trading/reserve_pool.py` manages an untouchable cash reserve that grows from realized execution gains. The reserve serves two purposes: it provides a buffer against peak-to-trough declines, and its size relative to the resource pool influences risk tier upgrade decisions.
### Profit Siphoning
When the engine detects a closed commitment with positive unrealized gain/loss (via `_sync_commitments_and_siphon()` in the performance loop), it calls `siphon_profit()` on the controller. The method transfers a configurable fraction of the realized gain into the reserve — by default 20% (`siphon_pct = 0.20`). Only positive gains are siphoned; losses do not reduce the reserve balance. Each siphon event is recorded in the `reserve_pool_ledger` table with the transfer amount, resulting balance, trigger type (`profit_siphon`), the entity as reference, and a timestamp.
### High-Water Mark Rebalancing
The `is_high_water()` method returns `True` when the reserve balance exceeds 30% of total resource pool value (`high_water_pct = 0.30`). This signal is consumed by the risk tier scheduler — when the reserve is healthy and other performance criteria are met, the controller may recommend upgrading to a more aggressive tier. The high-water mark acts as a confidence indicator: a large reserve means the system has been consistently successful and can afford to take on more risk.
### Emergency Liquidation
The `should_emergency_liquidate()` method checks whether the current peak-to-trough decline exceeds an emergency threshold. When triggered, `emergency_liquidate()` returns the full reserve balance for release back into the active pool. The caller (the engine) is responsible for zeroing the persisted balance and recording the ledger entry. Emergency liquidation is a last resort — it sacrifices the safety buffer to prevent the resource pool from hitting a catastrophic loss level.
### Active Pool Computation
The `compute_active_pool()` method calculates the capital available for execution: `active_pool = total_pool_value reserve_balance`. All commitment sizing computations use the active pool rather than the total resource pool value, ensuring that the reserve is never inadvertently deployed into new commitments.
---
## Risk Tier Auto-Adjustment
The `RiskTierController` in `services/trading/risk_tier_controller.py` evaluates resource pool performance and determines whether the active risk tier should shift. The system supports three tiers — conservative, moderate, and aggressive — each defined by a `RiskTierConfig` dataclass in `services/trading/models.py` with distinct parameter values:
| Parameter | Conservative | Moderate | Aggressive |
|-----------|-------------|----------|------------|
| `min_confidence` | 0.75 | 0.55 | 0.40 |
| `max_position_pct` | 5% | 10% | 15% |
| `stop_loss_atr_multiplier` | 1.5× | 2.0× | 2.5× |
| `reward_risk_ratio` | 2.0 | 1.5 | 1.2 |
| `max_sector_pct` | 20% | 30% | 40% |
| `max_portfolio_heat` | 10% | 20% | 30% |
The tier controller's `evaluate()` method checks two conditions:
**Downgrade (any one triggers).** If the trailing 30-day success rate drops below 40% or the current peak-to-trough decline exceeds 15%, the tier steps down by one level (e.g., aggressive → moderate). If the system is already at conservative, no further downgrade is possible.
**Upgrade (all must be true).** If the success rate exceeds 55%, the reserve pool exceeds 20% of total resource pool value, and the current peak-to-trough decline is below 5%, the tier steps up by one level. The triple requirement ensures that upgrades only happen when the system is performing well, has built a safety cushion, and is not in a decline.
The risk tier scheduler in the engine evaluates these conditions daily at session close. When a tier change occurs, it is persisted to the `risk_tier_history` table with the previous tier, new tier, trigger source (`auto_adjustment`), and the metrics that drove the decision (success rate, peak-to-trough decline, reserve percentage, risk-adjusted return ratio). The new tier takes effect immediately — the engine updates its `_active_risk_tier` reference, and all subsequent decision cycles use the new tier's parameters for confidence gates, commitment sizing, risk threshold computation, and sector exposure limits.
---
## Execution Request Submission Flow
When `evaluate_recommendation()` returns an `act` decision, the engine constructs an execution request job and pushes it through a multi-stage submission pipeline that spans two services.
### Decision Persistence
Every evaluation — whether it results in `act` or `skip` — produces a decision record that is persisted to the `execution_decisions` table via `_persist_decision()`. The record captures the recommendation ID, decision outcome, skip reason (if applicable), entity identifier, computed commitment size and unit quantity, the risk tier at the time of decision, pool exposure, active pool and reserve pool balances, circuit breaker status, correlation and sector exposure check results, performance report proximity flag, and a `decision_trace` JSONB field containing the full reasoning chain. This creates a complete audit record of every recommendation the engine evaluated and why it acted or declined.
### Execution Request Enqueue
For `act` decisions, the engine builds an execution request job dictionary containing the decision ID, entity identifier, action (act or defer), quantity, and request type (immediate). This job is pushed via `rpush` to the `app:queue:execution_orders` Redis queue (constructed by `queue_key(QUEUE_BROKER)` from `services/shared/redis_keys.py`). The engine immediately deducts the estimated execution cost from the in-memory active pool to prevent over-allocation across concurrent recommendation evaluations within the same polling cycle.
### Execution Service Processing
The execution service in `services/adapters/broker_service.py` runs as a standalone worker that polls `app:queue:execution_orders` via `blpop`. For each execution request job, `process_order_job()` executes a multi-step pipeline:
1. **Idempotency check.** A deterministic idempotency key is generated from the job's entity identifier, action, quantity, and decision ID. The service checks Redis first (fast path) and then the `orders` table (durable fallback) to prevent duplicate submissions. If a matching key exists, the job is silently dropped.
2. **Risk evaluation.** The service loads the current `PoolRiskConfig` from the database and the account's risk state (active commitments, daily gain/loss, sector exposure) from both the database and the external execution API. The `evaluate_order()` function runs the proposed execution request through a set of risk checks — commitment limits, sector concentration, daily loss thresholds — and produces an evaluation result. The evaluation is persisted to the `risk_evaluations` table regardless of outcome.
3. **External API submission.** If the risk evaluation passes, the service calls `submit_order()` on the `ExecutionAdapter` in `services/adapters/broker_adapter.py`. The adapter constructs the external execution API payload (entity identifier, quantity, side, request type, time in force) and submits it to `execution-api.example.com/v2/orders` with an idempotency key header. The adapter follows a fail-closed policy: any network error or ambiguous response returns a rejected `ExecutionResponse` rather than risking duplicate execution requests.
4. **Persistence and audit trail.** The `persist_order()` function writes the execution request to the `orders` table with the full request and response details, risk evaluation results, and the recommendation ID for traceability. When the execution request is filled, the fill details (value, quantity) are recorded. Execution request events are published to the analytical lakehouse via MinIO for downstream analysis. The Redis idempotency marker is set after successful persistence to prevent reprocessing.
The result is a complete chain of custody: from the original document that produced a signal (Pages [1](01-data-ingestion-and-preparation.md)[2](02-ai-agent-processing-and-extraction.md)), through signal scoring ([Page 3](03-signal-scoring-and-weighted-signals.md)) and trend aggregation ([Page 4](04-trend-aggregation-and-accumulating-signals.md)), to the recommendation ([Page 5](05-recommendation-generation.md)), the execution decision, the risk evaluation, and the execution response — every step is persisted and linked by foreign keys. The `execution_decisions` table links to `recommendations` via `recommendation_id`, the `orders` table links back to both, and the `commitments` and `pool_snapshots` tables capture the resource pool impact over time.
For additional reference on the decision execution engine's configuration, queue topology, and database tables, see [docs/services.md](../services.md).
---
## Conclusion: From Raw Data to Decision Execution
This six-page series has traced the full intelligence-to-decision pipeline, from the moment raw data enters the system to the moment an execution request reaches the external execution API.
It began with [Page 1](01-data-ingestion-and-preparation.md), where the scheduler orchestrates ingestion cycles across four data sources — external news, regulatory filings, external data feeds, and macro news APIs — and the parser normalizes raw content into structured documents ready for AI processing. [Page 2](02-ai-agent-processing-and-extraction.md) described how the Document Intelligence Extractor and Global Event Classifier agents use LLM inference to produce structured JSON intelligence, with hot-swappable model configurations and a robust JSON repair pipeline. [Page 3](03-signal-scoring-and-weighted-signals.md) explained how raw extraction output is transformed into `WeightedSignal` objects through a composite formula that balances recency, credibility, novelty, and environmental context across three independent signal layers. [Page 4](04-trend-aggregation-and-accumulating-signals.md) showed how the aggregation engine merges these signals across five time windows, detecting contradictions, ranking evidence, and computing trend projections — with consecutive same-direction signals accumulating to escalate the system's response from neutral through observe and monitor to act or defer. [Page 5](05-recommendation-generation.md) covered the translation of trend assessments into actionable recommendations through data quality suppression, eligibility evaluation, commitment sizing, thesis generation, and risk classification.
And here in Page 6, the pipeline reached its terminus: the decision execution engine's decision loop polling those recommendations, subjecting each to circuit breaker checks, confidence gates, deduplication, pool health assessments, and a multi-step commitment sizer — then submitting approved execution requests through the execution adapter to the external execution API, with every decision recorded in a fully auditable trail from signal to execution.
The pipeline is designed to be conservative by default and transparent throughout. Every stage applies its own safety checks — deduplication at ingestion, confidence gates at extraction, contradiction detection at aggregation, suppression at recommendation, and circuit breakers at execution. The system can be tuned through runtime configuration (risk tier parameters, suppression thresholds, signal layer toggles in `risk_configs`) without code changes or restarts. And the complete audit trail — from `documents` through `document_intelligence`, `document_impact_records`, `trend_windows`, `recommendations`, `execution_decisions`, and `orders` — means that any decision can be traced back to the specific documents, signals, and evaluations that produced it.
@@ -0,0 +1 @@
@@ -0,0 +1,94 @@
# Decision Execution Engine Loop
```mermaid
flowchart TD
subgraph ENGINE["Decision Execution Engine\nservices/trading/engine.py"]
direction TB
TASKS["5 Concurrent Async Tasks"]
T1["_decision_loop()\n60s polling interval"]
T2["_risk_threshold_monitor()"]
T3["_performance_loop()"]
T4["_risk_tier_scheduler()"]
T5["_rebalance_scheduler()"]
TASKS --> T1 & T2 & T3 & T4 & T5
end
T1 --> POLL["Poll recommendations table\naction IN (act, defer)\nmode IN (simulation_eligible, production_eligible)\ngenerated_at > NOW() 2h"]
POLL --> EVAL["evaluate_recommendation()"]
EVAL --> CHK_A
subgraph PRETRADE["Pre-Execution Check Sequence\n(first failure short-circuits)"]
direction TB
CHK_A["a. Circuit Breaker active?\nservices/trading/circuit_breaker.py\nTriggers: daily_loss, single_commitment, volatility"]
CHK_B["b. Execution Window?\nis_within_execution_window()"]
CHK_C["c. Confidence Gate\nconfidence ≥ risk_tier.min_confidence"]
CHK_D["d. Deduplication\nRec ID in processed set?\nRedis: app:dedupe:execution:*"]
CHK_E["e. Declining Commitments\n> 50% commitments down > 2%"]
CHK_F["f. Max Open Commitments\nopen_count ≥ max (default 10)"]
CHK_A -->|"pass"| CHK_B
CHK_B -->|"pass"| CHK_C
CHK_C -->|"pass"| CHK_D
CHK_D -->|"pass"| CHK_E
CHK_E -->|"pass"| CHK_F
end
CHK_A & CHK_B & CHK_C & CHK_D & CHK_E & CHK_F -->|"fail"| SKIP["ExecutionDecision\ndecision = skip\n+ skip_reason"]
CHK_F -->|"pass"| SIZER
subgraph SIZER["Commitment Sizing\nservices/trading/position_sizer.py"]
direction TB
SZ1["Base sizing\nrisk_tier.max_commitment_pct × 0.5\n× (confidence / min_confidence)"]
SZ2["Correlation reduction\nweighted avg corr > 0.8 → reject\n> 0.5 → proportional reduction"]
SZ3["Sector exposure\ncap at risk_tier.max_sector_pct"]
SZ4["Diversification bonus\n1.2× for new sector (< 3 sectors)"]
SZ5["Event proximity\n≤ 1 day → reject\n≤ 3 days → 50% reduction"]
SZ6["Absolute commitment cap"]
SZ7["Pool exposure check\nmax_pool_exposure × active_pool"]
SZ8["Share rounding\nfloor(dollar / price)"]
SZ1 --> SZ2 --> SZ3 --> SZ4 --> SZ5 --> SZ6 --> SZ7 --> SZ8
end
SIZER -->|"rejected"| SKIP
SIZER -->|"approved"| ACT["ExecutionDecision\ndecision = act\nshares, dollar amount"]
ACT --> PERSIST_TD["Persist to\nexecution_decisions"]
ACT --> ORDER["Build execution request\n{entity, action, side,\nquantity, request_type}"]
ORDER -->|"rpush"| Q_BROKER["app:queue:execution_orders"]
Q_BROKER --> BROKER["Execution Adapter\nexternal execution API (simulation)\nservices/adapters/broker_adapter.py"]
BROKER --> AUDIT
subgraph AUDIT["Audit Trail — PostgreSQL"]
AU1["execution_requests"]
AU2["commitments"]
AU3["pool_snapshots"]
end
subgraph CB_DETAIL["Circuit Breaker Detail\nservices/trading/circuit_breaker.py"]
CB1["daily_loss\npool loss > 5%\ncooldown: volatility_pause_hours"]
CB2["single_commitment\ncommitment loss > 15%\ncooldown: entity_cooldown_hours (48h)"]
CB3["volatility\n≥ 3 risk thresholds in 30min\ncooldown: volatility_pause_hours (2h)"]
CB4["Redis state\napp:execution:circuit_breaker:*"]
end
subgraph RESERVE["Reserve Pool\nservices/trading/reserve_pool.py"]
RP1["Profit siphoning: 20%"]
RP2["High-water rebalance: 30%"]
RP3["Emergency liquidation"]
RP4["reserve_pool_ledger"]
end
subgraph RISK_TIER["Risk Tier Auto-Adjustment\nservices/trading/risk_tier_controller.py"]
RT1["Evaluate: risk-adjusted return ratio,\npeak-to-trough decline, success rate"]
RT2["conservative → moderate → aggressive"]
RT3["risk_tier_history"]
end
```
@@ -0,0 +1,81 @@
# Ingestion-to-Extraction Flow
```mermaid
flowchart TD
subgraph Scheduler["Scheduler\nservices/scheduler/app.py"]
S1["schedule_cycle()"]
S2["Cadence check\nmarket_api: 300s\nnews_api: 300s\nfilings_api: 3600s\nmacro_news: 600s"]
S3["Rate limit check\ncheck_rate_limit()"]
S1 --> S2 --> S3
end
S3 -->|"rpush"| Q_ING["app:queue:ingestion"]
Q_ING -->|"lpop"| ING
subgraph ING["Ingestion Worker\nservices/ingestion/worker.py"]
direction TB
AD["Adapter Dispatch\nprocess_job()"]
AD --> PA["ExternalDataAdapter\nservices/adapters/market_adapter.py"]
AD --> PB["ExternalNewsAdapter\nservices/adapters/news_adapter.py"]
AD --> PC["RegulatoryFilingsAdapter\nservices/adapters/filings_adapter.py"]
AD --> PD["MacroNewsAdapter\nservices/adapters/macro_news_adapter.py"]
AD --> PE["WebScrapeAdapter\nservices/adapters/web_scrape_adapter.py"]
end
ING -->|"Content hash check\napp:dedupe:*\nTTL 24h"| REDIS_DEDUPE[("Redis\nDedupe Markers")]
ING -->|"upload_raw_artifact()"| MINIO_RAW
subgraph MINIO_RAW["MinIO Raw Storage"]
B1["app-raw-data"]
B2["app-raw-content"]
B3["app-raw-filings"]
end
ING -->|"persist_ingestion_items()"| PG_ING
subgraph PG_ING["PostgreSQL"]
T1["documents"]
T2["ingestion_runs"]
T3["document_company_mentions"]
end
ING -->|"rpush new doc IDs"| Q_PARSE["app:queue:parsing"]
Q_PARSE -->|"lpop"| PARSER
subgraph PARSER["Parser Worker\nservices/parser/worker.py"]
P1["fetch_html() → parse_html()"]
P2["Quality scoring\nconfidence: high / medium / low"]
P3["Company mention detection\ndetect_company_mentions()"]
P4["Routing decision"]
P1 --> P2 --> P3 --> P4
end
PARSER -->|"upload_normalized_text()\nupload_parser_output()"| MINIO_NORM["MinIO\napp-normalized"]
PARSER -->|"update_document_parse_results()"| PG_ING
P4 -->|"doc_type = macro_event"| Q_MACRO["app:queue:macro_classification"]
P4 -->|"doc_type ≠ macro_event"| Q_EXT["app:queue:extraction"]
Q_EXT -->|"lpop"| EXT
Q_MACRO -->|"lpop"| EXT
subgraph EXT["Extractor Worker\nservices/extractor/main.py"]
E1["Document Intelligence\nExtractor agent\nslug: document-extractor"]
E2["Global Event Classifier\nslug: event-classifier\nservices/extractor/event_classifier.py"]
E3["persist_extraction()\nservices/extractor/worker.py"]
end
EXT -->|"persist to"| PG_EXT
subgraph PG_EXT["PostgreSQL"]
T4["document_intelligence"]
T5["document_impact_records"]
T6["global_events"]
T7["macro_impact_records"]
end
EXT -->|"rpush"| Q_AGG["app:queue:aggregation"]
```
@@ -0,0 +1,80 @@
# Recommendation Generation Flow
```mermaid
flowchart TD
Q_REC["app:queue:recommendation"] -->|"lpop"| WORKER["Recommendation Worker\nservices/recommendation/main.py"]
WORKER --> FETCH["Fetch TrendSummary\nfrom trend_windows\nfor entity + window"]
FETCH --> SUPP
subgraph SUPP["Data Quality Suppression\nservices/recommendation/suppression.py"]
S1["extraction confidence < 0.40?"]
S2["evidence staleness > 168h?"]
S3["source diversity < 1 type?"]
S4["extraction failure rate > 50%?"]
S5["valid documents < 2?"]
S6["data quality score < 0.30?"]
S7["Macro-only signal?\nevaluate_macro_only_suppression()"]
S8["Pattern-only signal?\nevaluate_pattern_only_suppression()"]
end
SUPP -->|"Any check fails:\nsuppressed = true\nmode → informational"| ELIG
SUPP -->|"All checks pass"| ELIG
subgraph ELIG["Eligibility Evaluation\nservices/recommendation/eligibility.py"]
direction TB
G["Gate Checks"]
G1["confidence ≥ 0.35"]
G2["strength ≥ 0.10"]
G3["contradiction ≤ 0.60"]
G4["evidence ≥ 2"]
G5["direction ≠ neutral"]
G --> G1 & G2 & G3 & G4 & G5
G1 & G2 & G3 & G4 & G5 --> ACT["Action Mapping"]
ACT --> A1["ACT: positive + strength ≥ 0.25"]
ACT --> A2["DEFER: negative + strength ≥ 0.25"]
ACT --> A3["MONITOR: directional + confidence ≥ 0.50"]
ACT --> A4["OBSERVE: otherwise"]
A1 & A2 & A3 & A4 --> MODE["Mode Escalation"]
MODE --> M1["informational\n(default for MONITOR/OBSERVE)"]
MODE --> M2["simulation_eligible\nconfidence ≥ 0.50"]
MODE --> M3["production_eligible\nconfidence ≥ 0.70\ncontradiction ≤ 0.25\nevidence ≥ 5"]
end
ELIG --> SIZING
subgraph SIZING["Commitment Sizing\nservices/recommendation/eligibility.py"]
PS1["base = 1% allocation pool"]
PS2["scale by confidence × strength\nup to 10% max"]
PS3["contradiction penalty\n0.5 × contradiction_score"]
PS4["evidence count penalty\n< 3 docs → ×0.5\n< 5 docs → ×0.75"]
end
SIZING --> THESIS
subgraph THESIS["Thesis Generation"]
TH1["Deterministic thesis\nassembled from trend data"]
TH2["Optional LLM rewrite\nthesis-rewriter agent\nservices/recommendation/thesis_llm.py"]
TH1 --> TH2
end
THESIS --> RISK
subgraph RISK["Risk Classification"]
RC1["low"]
RC2["moderate"]
RC3["high"]
RC4["very_high"]
end
RISK --> PERSIST
subgraph PERSIST["Persistence — PostgreSQL"]
P1["recommendations"]
P2["recommendation_evidence"]
P3["risk_evaluations"]
end
```
@@ -0,0 +1,52 @@
# Three-Layer Signal Merging
```mermaid
flowchart TD
subgraph Layer1["Layer 1 — Entity Signals"]
DIR["document_impact_records\n(per-entity extraction output)"]
DIR -->|"build_weighted_signals()"| WS1["WeightedSignal[]\nweight = 1.0 (full)"]
end
subgraph Layer2["Layer 2 — Macro Signals"]
MIR["macro_impact_records\n(global event interpolation)"]
MIR -->|"build_macro_weighted_signals()"| WS2["WeightedSignal[]\nimpact × MACRO_SIGNAL_WEIGHT\n(0.3)"]
TOGGLE_M{"macro_enabled\nin risk_configs?"}
TOGGLE_M -->|"true"| MIR
TOGGLE_M -->|"false"| SKIP_M["Layer skipped\ngraceful degradation"]
end
subgraph Layer3["Layer 3 — Competitive Signals"]
CSR["competitive_signal_records\n(pattern mining + propagation)"]
CSR -->|"build_pattern_weighted_signals()\nservices/aggregation/signal_propagation.py"| WS3["WeightedSignal[]\nimpact × COMPETITIVE_SIGNAL_WEIGHT\n(0.2)"]
TOGGLE_C{"competitive_enabled\nin risk_configs?"}
TOGGLE_C -->|"true"| CSR
TOGGLE_C -->|"false"| SKIP_C["Layer skipped\ngraceful degradation"]
end
WS1 --> MERGE["Concatenate all WeightedSignal lists"]
WS2 --> MERGE
WS3 --> MERGE
MERGE --> AGG
subgraph AGG["Aggregation Engine\nservices/aggregation/worker.py"]
A1["weighted_sentiment_average()"]
A2["detect_contradictions()\nservices/aggregation/contradiction.py"]
A3["derive_trend_direction()"]
A4["compute_trend_confidence()"]
A5["rank_evidence()"]
A1 --> A2 --> A3 --> A4 --> A5
end
AGG -->|"assemble_trend_summary()"| TS["TrendSummary\nservices/shared/schemas.py"]
TS -->|"persist_trend_summary()"| PG_TREND
subgraph PG_TREND["PostgreSQL"]
TW["trend_windows\n(upserted each cycle)"]
TH["trend_history\n(time-series snapshots)"]
TE["trend_evidence\n(per-document rankings)"]
end
AGG -->|"rpush"| Q_REC["app:queue:recommendation"]
```
@@ -0,0 +1,62 @@
# Trend Accumulation and Escalation
```mermaid
flowchart TD
subgraph Windows["Five Time Windows\nservices/aggregation/worker.py"]
W1["intraday (12h)"]
W2["1d (1 day)"]
W3["7d (7 days)"]
W4["30d (30 days)"]
W5["90d (90 days)"]
end
W1 & W2 & W3 & W4 & W5 --> SIGNALS
SIGNALS["Fetch signals per window\nEntity + Macro + Competitive\n→ WeightedSignal[]"]
SIGNALS --> SENT["weighted_sentiment_average()\nCompute avg sentiment across signals"]
SENT --> DIR
subgraph DIR["derive_trend_direction()"]
D1["avg_sentiment ≥ 0.15 → POSITIVE"]
D2["avg_sentiment ≤ 0.15 → NEGATIVE"]
D3["contradiction > 0.10\nAND |avg| < 0.30 → MIXED"]
D4["otherwise → NEUTRAL"]
end
DIR --> CONF
subgraph CONF["compute_trend_confidence()"]
C1["Unique source count\ncaps at 15 → 0.8 contribution"]
C2["Avg extraction credibility"]
C3["Signal agreement ratio\ndampened by log₂(n+1)/log₂(8)\nsaturates ~7 unique sources"]
C4["Contradiction penalty\n0.4 × contradiction_score"]
C5["confidence = 0.3×count + 0.3×credibility\n+ 0.4×agreement penalty"]
end
CONF --> STRENGTH["trend_strength = |avg_sentiment|\nclamped to [0, 1]"]
STRENGTH --> ESC
subgraph ESC["Escalation Path\n(via eligibility thresholds)"]
direction TB
E1["NEUTRAL\nconfidence < 0.35\nOR strength < 0.10\nOR direction = neutral"]
E2["OBSERVE\nstrength < 0.25\nAND confidence < 0.50"]
E3["MONITOR\nstrength < 0.25\nAND confidence ≥ 0.50"]
E4["ACT / DEFER\nstrength ≥ 0.25\nAND direction = positive/negative"]
E1 -->|"More signals\nsame direction"| E2
E2 -->|"Confidence grows\nmore unique sources"| E3
E3 -->|"Strength exceeds 0.25\naccumulated evidence"| E4
end
ESC --> PERSIST
subgraph PERSIST["Persistence"]
P1["trend_windows\n(upserted each cycle)"]
P2["trend_history\n(time-series snapshots)"]
P3["trend_evidence\n(per-document rankings)"]
P4["trend_projections\nservices/aggregation/projection.py"]
end
```
@@ -0,0 +1,58 @@
# Weighted Signal Computation
```mermaid
flowchart TD
DOC["Document Signal Input\n(published_at, source_credibility,\nnovelty_score, extraction_confidence,\nmarket_ctx)"]
DOC --> GATE
DOC --> REC
DOC --> CRED
DOC --> NOV
DOC --> MKT
subgraph GATE["Confidence Gate"]
G1["extraction_confidence ≥ 0.2?"]
G1 -->|"Yes"| G2["gate = 1.0"]
G1 -->|"No"| G3["gate = 0.0\n(signal zeroed out)"]
end
subgraph REC["Recency Decay"]
R1["w = 2^(age_hours / half_life)"]
R2["Half-lives per window:\nintraday: 2h\n1d: 12h\n7d: 72h\n30d: 240h\n90d: 720h"]
R3["Floor: min_recency_weight = 0.01"]
R1 --- R2
R1 --- R3
end
subgraph CRED["Source Credibility"]
C1["Clamp to [0.1, 1.0]"]
C2["Apply exponent\n(default 1.0)"]
C1 --> C2
end
subgraph NOV["Novelty Bonus"]
N1["bonus = novelty_score × 0.25"]
N2["Range: [0.0, 0.25]\n(up to 25% boost)"]
N1 --- N2
end
subgraph MKT["Environmental Context Multiplier"]
M1["Volatility boost\nlog₁₊(excess) × 0.15\ncapped at 0.30"]
M2["Volume surge boost\nvolume_change > 50% → +0.15"]
M3["multiplier = 1.0 + boost\n(always ≥ 1.0)"]
M1 --> M3
M2 --> M3
end
GATE --> FORMULA
REC --> FORMULA
CRED --> FORMULA
NOV --> FORMULA
MKT --> FORMULA
FORMULA["combined = gate × recency × credibility\n× (1 + novelty_bonus)\n× market_context_multiplier"]
FORMULA --> SW["SignalWeight\nservices/aggregation/scoring.py"]
SW --> WS["WeightedSignal\n{ document_id, weight: SignalWeight,\nsentiment_value, impact_score }"]
```
@@ -0,0 +1,39 @@
# Intelligence Pipeline Deep Dive
This document series provides a narrative walkthrough of the full intelligence-to-decision pipeline in the platform. Unlike the existing service reference and API documentation, these pages tell the story of how raw data enters the system, gets processed by AI agents, produces structured signals, accumulates into trend summaries, and ultimately drives autonomous decision execution.
Each page covers one stage of the pipeline and ends with a transition to the next, so you can read the series end-to-end or jump directly to the stage you need. Diagrams are stored as standalone Mermaid files that can be rendered independently or embedded in other documents.
---
## Table of Contents
1. [Data Ingestion and Preparation](01-data-ingestion-and-preparation.md) — How raw data from an external data provider, a public records API, and macro news APIs enters the system, gets deduplicated, stored, parsed, and routed for AI processing.
2. [AI Agent Processing and Structured Extraction](02-ai-agent-processing-and-extraction.md) — How the Document Intelligence Extractor and Global Event Classifier agents use LLM inference to produce structured JSON intelligence from documents.
3. [Signal Scoring and the WeightedSignal Abstraction](03-signal-scoring-and-weighted-signals.md) — How raw extraction output is transformed into weighted signals through confidence gating, recency decay, source credibility, novelty bonuses, and environmental context multipliers.
4. [Trend Aggregation and Accumulating Signals](04-trend-aggregation-and-accumulating-signals.md) — How the aggregation engine merges weighted signals across five time windows, detects contradictions, ranks evidence, and escalates trend strength as consecutive signals accumulate.
5. [Recommendation Generation](05-recommendation-generation.md) — How trend summaries pass through data quality suppression, eligibility evaluation, commitment sizing, thesis generation, and risk classification to produce actionable recommendations.
6. [Decision Execution](06-decision-execution.md) — How the decision execution engine polls recommendations, runs pre-execution checks, sizes commitments, enforces circuit breakers, and submits execution requests through the execution adapter.
---
## Diagrams
The following Mermaid diagram files can be rendered independently or referenced from the narrative pages:
- [Ingestion to Extraction Flow](diagrams/ingestion-to-extraction-flow.md) — Flowchart from Scheduler through Ingestion, Parser, to Extractor with all queues and storage.
- [Three-Layer Signal Merging](diagrams/three-layer-signal-merging.md) — Entity-specific, Environmental, and Relational signal layers converging into the Aggregation engine.
- [Weighted Signal Computation](diagrams/weighted-signal-computation.md) — Component breakdown of the composite weight formula.
- [Trend Accumulation and Escalation](diagrams/trend-accumulation-escalation.md) — How consecutive signals strengthen trends and escalate actions across time windows.
- [Recommendation Generation Flow](diagrams/recommendation-generation-flow.md) — From TrendSummary through suppression, eligibility, thesis, risk classification, to persistence.
- [Decision Engine Loop](diagrams/decision-engine-loop.md) — Pre-execution check sequence, commitment sizing, and execution request submission flow.
---
## Related Documentation
For reference-level detail on individual services, AI agent configuration, and infrastructure, see the existing documentation:
- [Services Reference](../services.md) — Per-service configuration, database tables, queues, and runtime behaviors.
- [AI Agents Guide](../ai-agents.md) — AI agent configuration, variants, A/B testing, and the agent management API.
- [Data Pipeline Architecture](../architecture-data-pipeline.md) — Queue topology, data store summary, and Mermaid flow diagrams for the full data pipeline.
+1052
View File
File diff suppressed because it is too large Load Diff
+7 -1
View File
@@ -662,12 +662,18 @@ export interface CompetitiveSignal {
}
export function useCompetitiveSignals(ticker: string | undefined) {
return useGet<CompetitiveSignal[]>(
const result = useGet<CompetitiveSignal[] | { competitive_signals: CompetitiveSignal[] }>(
['competitive-signals', ticker],
'query',
`/api/patterns/${ticker}/competitive-signals`,
!!ticker,
);
// API returns { competitive_signals: [...] } wrapper — extract the array
const data = result.data;
const signals: CompetitiveSignal[] | undefined = data
? (Array.isArray(data) ? data : (data as { competitive_signals: CompetitiveSignal[] }).competitive_signals ?? [])
: undefined;
return { ...result, data: signals };
}
// ---------------------------------------------------------------------------
+2
View File
@@ -22,6 +22,8 @@ export interface TradingEngineStatus {
portfolio_heat: number;
portfolio_value: number;
open_position_count: number;
max_open_positions: number;
absolute_position_cap: number;
last_decision_at: string | null;
micro_trading_enabled: boolean;
uptime_seconds: number | null;
+194 -76
View File
@@ -1,4 +1,4 @@
import { useParams, useNavigate } from '@tanstack/react-router';
import { useParams, useNavigate, Link } from '@tanstack/react-router';
import { useState } from 'react';
import {
useCompany,
@@ -14,6 +14,8 @@ import {
useTrends,
useTrendHistory,
useMarketPrices,
useDocument,
usePositions,
} from '../api/hooks';
import { StatusBadge, ConfidenceBar, LoadingSpinner, Card } from '../components/ui';
import { DataTable, type Column } from '../components/DataTable';
@@ -42,8 +44,10 @@ export function CompanyDetailPage() {
const { data: signals } = useCompetitiveSignals(company?.ticker);
const { data: decisions } = useCorporateDecisions(company?.ticker);
const { data: trends } = useTrends({ ticker: company?.ticker, limit: 200 });
const { data: trendHistory } = useTrendHistory({ ticker: company?.ticker, limit: 500 });
const [selectedWindow, setSelectedWindow] = useState('7d');
const { data: trendHistory } = useTrendHistory({ ticker: company?.ticker, window: selectedWindow, limit: 500 });
const { data: marketPrices } = useMarketPrices(company?.ticker, 200);
const { data: positions } = usePositions(company?.ticker);
const [tab, setTab] = useState<'trends' | 'sources' | 'aliases' | 'macro' | 'competitors' | 'patterns' | 'signals' | 'decisions'>('trends');
if (isLoading || !company) return <LoadingSpinner />;
@@ -82,7 +86,10 @@ export function CompanyDetailPage() {
</div>
{tab === 'trends' && (
<TrendHistoryChart trends={trendHistory ?? []} latestTrends={trends ?? []} ticker={company.ticker} marketPrices={marketPrices ?? []} />
<div className="space-y-4">
<PositionCard positions={positions ?? []} ticker={company.ticker} />
<TrendHistoryChart trends={trendHistory ?? []} latestTrends={trends ?? []} ticker={company.ticker} marketPrices={marketPrices ?? []} selectedWindow={selectedWindow} onWindowChange={setSelectedWindow} />
</div>
)}
{tab === 'sources' && (
@@ -444,62 +451,7 @@ function CompetitiveSignalsPanel({ signals }: { signals: CompetitiveSignal[] })
) : (
<div className="space-y-2">
{signals.map((s) => (
<div key={s.id}>
<div
className="flex items-center justify-between rounded-lg border border-cyan-700/30 bg-cyan-900/10 p-3 cursor-pointer hover:border-cyan-500/50"
onClick={() => setExpandedId(expandedId === s.id ? null : s.id)}
>
<div className="flex items-center gap-3">
<span className="rounded bg-cyan-900/40 border border-cyan-700/50 px-1.5 py-0.5 text-[10px] font-medium text-cyan-400">COMPETITIVE</span>
<span className="font-mono text-sm text-brand-300">{s.source_ticker}</span>
<span className="text-xs text-gray-400"></span>
<StatusBadge status={s.catalyst_type} />
<StatusBadge status={s.signal_direction} />
</div>
<div className="flex items-center gap-3">
<ConfidenceBar value={s.signal_strength} />
<span className="text-xs text-gray-500">{new Date(s.computed_at).toLocaleDateString()}</span>
</div>
</div>
{expandedId === s.id && (
<Card className="mt-1 ml-4">
<dl className="grid grid-cols-2 gap-x-6 gap-y-2 text-xs sm:grid-cols-3">
<div>
<dt className="text-gray-500">Source Ticker</dt>
<dd className="font-mono text-gray-200">{s.source_ticker}</dd>
</div>
<div>
<dt className="text-gray-500">Target Ticker</dt>
<dd className="font-mono text-gray-200">{s.target_ticker}</dd>
</div>
<div>
<dt className="text-gray-500">Catalyst Type</dt>
<dd className="text-gray-200">{s.catalyst_type}</dd>
</div>
<div>
<dt className="text-gray-500">Pattern Confidence</dt>
<dd><ConfidenceBar value={s.pattern_confidence} /></dd>
</div>
<div>
<dt className="text-gray-500">Signal Strength</dt>
<dd><ConfidenceBar value={s.signal_strength} /></dd>
</div>
<div>
<dt className="text-gray-500">Relationship Strength</dt>
<dd><ConfidenceBar value={s.relationship_strength} /></dd>
</div>
<div>
<dt className="text-gray-500">Source Document</dt>
<dd className="font-mono text-gray-400 text-[10px]">{s.source_document_id}</dd>
</div>
<div>
<dt className="text-gray-500">Computed At</dt>
<dd className="text-gray-200">{new Date(s.computed_at).toLocaleString()}</dd>
</div>
</dl>
</Card>
)}
</div>
<SignalRow key={s.id} signal={s} expanded={expandedId === s.id} onToggle={() => setExpandedId(expandedId === s.id ? null : s.id)} />
))}
</div>
)}
@@ -507,6 +459,88 @@ function CompetitiveSignalsPanel({ signals }: { signals: CompetitiveSignal[] })
);
}
function SignalRow({ signal: s, expanded, onToggle }: { signal: CompetitiveSignal; expanded: boolean; onToggle: () => void }) {
const { data: doc } = useDocument(s.source_document_id);
const docLabel = doc?.title ?? `doc:${s.source_document_id.slice(0, 8)}`;
return (
<div>
<div
className="flex items-center justify-between rounded-lg border border-cyan-700/30 bg-cyan-900/10 p-3 cursor-pointer hover:border-cyan-500/50"
onClick={onToggle}
>
<div className="flex items-center gap-3">
<span className="rounded bg-cyan-900/40 border border-cyan-700/50 px-1.5 py-0.5 text-[10px] font-medium text-cyan-400">COMPETITIVE</span>
<span className="font-mono text-sm text-brand-300">{s.source_ticker}</span>
<span className="text-xs text-gray-400"></span>
<StatusBadge status={s.catalyst_type} />
<StatusBadge status={s.signal_direction} />
</div>
<div className="flex items-center gap-3">
<Link
to="/documents/$id"
params={{ id: s.source_document_id }}
className="max-w-[180px] truncate text-xs text-brand-400 hover:underline"
onClick={(e) => e.stopPropagation()}
title={doc?.title ?? s.source_document_id}
>
{docLabel}
</Link>
<ConfidenceBar value={s.signal_strength} />
<span className="text-xs text-gray-500">{new Date(s.computed_at).toLocaleDateString()}</span>
</div>
</div>
{expanded && (
<Card className="mt-1 ml-4">
<dl className="grid grid-cols-2 gap-x-6 gap-y-2 text-xs sm:grid-cols-3">
<div>
<dt className="text-gray-500">Source Ticker</dt>
<dd className="font-mono text-gray-200">{s.source_ticker}</dd>
</div>
<div>
<dt className="text-gray-500">Target Ticker</dt>
<dd className="font-mono text-gray-200">{s.target_ticker}</dd>
</div>
<div>
<dt className="text-gray-500">Catalyst Type</dt>
<dd className="text-gray-200">{s.catalyst_type}</dd>
</div>
<div>
<dt className="text-gray-500">Pattern Confidence</dt>
<dd><ConfidenceBar value={s.pattern_confidence} /></dd>
</div>
<div>
<dt className="text-gray-500">Signal Strength</dt>
<dd><ConfidenceBar value={s.signal_strength} /></dd>
</div>
<div>
<dt className="text-gray-500">Relationship Strength</dt>
<dd><ConfidenceBar value={s.relationship_strength} /></dd>
</div>
<div>
<dt className="text-gray-500">Source Document</dt>
<dd>
<Link
to="/documents/$id"
params={{ id: s.source_document_id }}
className="text-brand-400 hover:underline"
onClick={(e) => e.stopPropagation()}
>
{docLabel}
</Link>
</dd>
</div>
<div>
<dt className="text-gray-500">Computed At</dt>
<dd className="text-gray-200">{new Date(s.computed_at).toLocaleString()}</dd>
</div>
</dl>
</Card>
)}
</div>
);
}
function DecisionsPanel({ decisions }: { decisions: CorporateDecision[] }) {
return (
<div className="space-y-4">
@@ -568,13 +602,30 @@ interface ChartPoint {
price?: number;
}
function ChartXTick({ x, y, payload }: { x?: number; y?: number; payload?: { value: number } }) {
if (!payload || !x || !y) return null;
const d = new Date(payload.value);
const dateStr = d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
const timeStr = d.toLocaleTimeString('en-US', { hour: 'numeric', hour12: true });
return (
<g transform={`translate(${x},${y + 4})`}>
<text x={0} y={0} textAnchor="end" fontSize={10} transform="rotate(-35)">
<tspan fill="#e2e8f0" fontWeight="bold">{dateStr} </tspan>
<tspan fill="#94a3b8">{timeStr}</tspan>
</text>
</g>
);
}
function TrendTooltip({ active, payload, label }: Record<string, unknown>) {
if (!active) return null;
const items = payload as Array<{ name: string; value: number; color: string; dataKey: string }> | undefined;
if (!items?.length) return null;
const ts = typeof label === 'number' ? new Date(label).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : String(label ?? '');
return (
<div className="rounded-lg border border-surface-700 bg-surface-900 px-3 py-2 text-xs shadow-lg">
<div className="mb-1 text-gray-400">{String(label ?? '')}</div>
<div className="mb-1 text-gray-400">{ts}</div>
{items.map((item, i) => (
<div key={i} className="flex justify-between gap-4" style={{ color: item.color }}>
<span>{item.name}:</span>
@@ -587,12 +638,64 @@ function TrendTooltip({ active, payload, label }: Record<string, unknown>) {
);
}
function TrendHistoryChart({ trends, latestTrends, ticker, marketPrices }: { trends: TrendSummary[]; latestTrends: TrendSummary[]; ticker: string; marketPrices: MarketPrice[] }) {
const [selectedWindow, setSelectedWindow] = useState('7d');
function PositionCard({ positions, ticker }: { positions: import('../api/hooks').Position[]; ticker: string }) {
const pos = positions.find((p) => p.ticker === ticker && p.quantity > 0);
if (!pos) return null;
// Use history data for charts
const marketValue = pos.current_price ? pos.quantity * pos.current_price : null;
const pnlColor = (pos.unrealized_pnl ?? 0) >= 0 ? 'text-green-400' : 'text-red-400';
const pnlSign = (pos.unrealized_pnl ?? 0) >= 0 ? '+' : '';
return (
<Card>
<div className="flex items-center justify-between">
<h2 className="text-sm font-medium text-gray-400">Open Position</h2>
<StatusBadge status="active" />
</div>
<dl className="mt-2 grid grid-cols-2 gap-x-8 gap-y-2 text-sm sm:grid-cols-5">
<div>
<dt className="text-gray-500">Shares</dt>
<dd className="font-mono text-gray-200">{pos.quantity}</dd>
</div>
<div>
<dt className="text-gray-500">Avg Entry</dt>
<dd className="font-mono text-gray-200">${pos.avg_entry_price.toFixed(2)}</dd>
</div>
<div>
<dt className="text-gray-500">Current Price</dt>
<dd className="font-mono text-gray-200">{pos.current_price ? `$${pos.current_price.toFixed(2)}` : '—'}</dd>
</div>
<div>
<dt className="text-gray-500">Market Value</dt>
<dd className="font-mono text-gray-200">{marketValue ? `$${marketValue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : '—'}</dd>
</div>
<div>
<dt className="text-gray-500">Unrealized P&L</dt>
<dd className={`font-mono font-semibold ${pnlColor}`}>
{pos.unrealized_pnl != null ? `${pnlSign}$${Math.abs(pos.unrealized_pnl).toFixed(2)}` : '—'}
</dd>
</div>
</dl>
</Card>
);
}
function TrendHistoryChart({ trends, latestTrends, ticker, marketPrices, selectedWindow, onWindowChange }: { trends: TrendSummary[]; latestTrends: TrendSummary[]; ticker: string; marketPrices: MarketPrice[]; selectedWindow: string; onWindowChange: (w: string) => void }) {
// Determine the time range for the selected window to filter data
const windowHours: Record<string, number> = {
intraday: 24,
'1d': 48,
'7d': 7 * 24,
'30d': 30 * 24,
'90d': 90 * 24,
};
const hoursBack = windowHours[selectedWindow] ?? 7 * 24;
const cutoffTs = Date.now() - hoursBack * 3600_000;
// Use history data for charts — filter to selected window and time range
const filtered = (trends ?? [])
.filter((t) => t.entity_id === ticker && t.window === selectedWindow)
.filter((t) => t.entity_id === ticker && t.window === selectedWindow && new Date(t.generated_at).getTime() >= cutoffTs)
.sort((a, b) => new Date(a.generated_at).getTime() - new Date(b.generated_at).getTime());
// Build a price lookup — match by closest timestamp to each trend point
@@ -600,19 +703,30 @@ function TrendHistoryChart({ trends, latestTrends, ticker, marketPrices }: { tre
.filter((p) => p.bar_timestamp != null && p.close != null)
.sort((a, b) => a.bar_timestamp - b.bar_timestamp);
// Filter prices to the selected window's time range (use all prices if sparse)
const windowPrices = sortedPrices.length <= 20 ? sortedPrices : sortedPrices.filter((p) => p.bar_timestamp >= cutoffTs);
function findClosestPrice(ts: number): number | undefined {
if (sortedPrices.length === 0) return undefined;
let best = sortedPrices[0];
if (windowPrices.length === 0) return undefined;
let best = windowPrices[0];
let bestDiff = Math.abs(ts - best.bar_timestamp);
for (const p of sortedPrices) {
for (const p of windowPrices) {
const diff = Math.abs(ts - p.bar_timestamp);
if (diff < bestDiff) {
best = p;
bestDiff = diff;
}
}
// Only match if within 2 hours (for intraday) or 36 hours (for daily)
const maxGap = selectedWindow === 'intraday' ? 2 * 3600_000 : 36 * 3600_000;
// Match if within reasonable gap for the window type
// With sparse price data (~1 bar per 4-6 hours), use wider tolerances
const maxGapHours: Record<string, number> = {
intraday: 6,
'1d': 12,
'7d': 36,
'30d': 72,
'90d': 168,
};
const maxGap = (maxGapHours[selectedWindow] ?? 36) * 3600_000;
return bestDiff <= maxGap ? best.close : undefined;
}
@@ -620,7 +734,7 @@ function TrendHistoryChart({ trends, latestTrends, ticker, marketPrices }: { tre
const trendTs = new Date(t.generated_at).getTime();
const price = findClosestPrice(trendTs);
return {
time: new Date(t.generated_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }),
time: String(trendTs),
timestamp: trendTs,
strength: +(t.trend_strength * 100).toFixed(1),
confidence: +(t.confidence * 100).toFixed(1),
@@ -653,7 +767,7 @@ function TrendHistoryChart({ trends, latestTrends, ticker, marketPrices }: { tre
{(availableWindows.length > 0 ? availableWindows : WINDOW_ORDER).map((w) => (
<button
key={w}
onClick={() => setSelectedWindow(w)}
onClick={() => onWindowChange(w)}
className={`rounded-md px-3 py-1 text-xs font-medium transition-colors ${
selectedWindow === w
? 'bg-brand-600 text-white'
@@ -677,12 +791,16 @@ function TrendHistoryChart({ trends, latestTrends, ticker, marketPrices }: { tre
Trend Strength & Confidence {ticker} / {selectedWindow}
</h2>
<ResponsiveContainer width="100%" height={280}>
<LineChart data={chartData} margin={{ top: 5, right: 20, bottom: 5, left: 0 }}>
<LineChart data={chartData} margin={{ top: 5, right: 20, bottom: 40, left: 0 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#334155" />
<XAxis
dataKey="time"
tick={{ fill: '#94a3b8', fontSize: 11 }}
dataKey="timestamp"
type="number"
domain={['dataMin', 'dataMax']}
scale="time"
tick={<ChartXTick />}
tickLine={{ stroke: '#475569' }}
tickCount={8}
/>
<YAxis
yAxisId="left"
@@ -764,13 +882,13 @@ function TrendHistoryChart({ trends, latestTrends, ticker, marketPrices }: { tre
'bg-gray-600';
const height = Math.max(8, pt.strength * 0.5);
return (
<div key={i} className="flex flex-col items-center gap-1" title={`${pt.time}: ${pt.directionLabel} (${pt.strength}%)`}>
<div key={i} className="flex flex-col items-center gap-1" title={`${new Date(pt.timestamp).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })}: ${pt.directionLabel} (${pt.strength}%)`}>
<div
className={`w-3 rounded-sm ${color}`}
style={{ height: `${height}px` }}
/>
{i % Math.max(1, Math.floor(chartData.length / 8)) === 0 && (
<span className="text-[9px] text-gray-500 -rotate-45 origin-top-left whitespace-nowrap">{pt.time}</span>
<span className="text-[9px] text-gray-500 -rotate-45 origin-top-left whitespace-nowrap">{new Date(pt.timestamp).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}</span>
)}
</div>
);
+51 -2
View File
@@ -2,6 +2,55 @@ import { useParams } from '@tanstack/react-router';
import { useOrder } from '../api/hooks';
import { StatusBadge, LoadingSpinner, Card } from '../components/ui';
/**
* Lightweight JSON syntax highlighter for read-only display.
* Returns React elements with colored spans for keys, strings, numbers, booleans, and null.
*/
function highlightJson(json: string): React.ReactNode {
const parts: React.ReactNode[] = [];
// Regex matches JSON tokens: strings, numbers, booleans, null, and structural chars
const tokenRe = /("(?:\\.|[^"\\])*")\s*:|("(?:\\.|[^"\\])*")|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|(\btrue\b|\bfalse\b)|(\bnull\b)|([{}[\],])/g;
let lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = tokenRe.exec(json)) !== null) {
// Add any whitespace/text between tokens
if (match.index > lastIndex) {
parts.push(json.slice(lastIndex, match.index));
}
if (match[1]) {
// Key (string followed by colon)
parts.push(<span key={match.index} className="text-cyan-400">{match[1]}</span>);
parts.push(':');
} else if (match[2]) {
// String value
parts.push(<span key={match.index} className="text-green-400">{match[2]}</span>);
} else if (match[3]) {
// Number
parts.push(<span key={match.index} className="text-yellow-300">{match[3]}</span>);
} else if (match[4]) {
// Boolean
parts.push(<span key={match.index} className="text-purple-400">{match[4]}</span>);
} else if (match[5]) {
// Null
parts.push(<span key={match.index} className="text-red-400">{match[5]}</span>);
} else if (match[6]) {
// Structural characters
parts.push(<span key={match.index} className="text-gray-500">{match[6]}</span>);
}
lastIndex = match.index + match[0].length;
}
// Remaining text
if (lastIndex < json.length) {
parts.push(json.slice(lastIndex));
}
return <>{parts}</>;
}
export function OrderDetailPage() {
const { id } = useParams({ from: '/orders/$id' });
const { data: order, isLoading } = useOrder(id);
@@ -33,8 +82,8 @@ export function OrderDetailPage() {
{order.decision_trace && Object.keys(order.decision_trace).length > 0 && (
<Card>
<h2 className="mb-2 text-sm font-medium text-gray-400">Decision Trace</h2>
<pre className="overflow-x-auto rounded bg-surface-950 p-3 text-xs text-gray-300">
{JSON.stringify(order.decision_trace, null, 2)}
<pre className="overflow-x-auto rounded bg-surface-950 p-3 text-xs leading-relaxed">
{highlightJson(JSON.stringify(order.decision_trace, null, 2))}
</pre>
</Card>
)}
+33 -12
View File
@@ -1,4 +1,5 @@
import { usePositions } from '../api/hooks';
import { Link } from '@tanstack/react-router';
import { usePositions, useCompanies } from '../api/hooks';
import { DataTable, type Column } from '../components/DataTable';
import { LoadingSpinner } from '../components/ui';
import type { Position } from '../api/hooks';
@@ -13,18 +14,38 @@ function pnlColor(v: number | null | undefined) {
return v >= 0 ? 'text-green-400' : 'text-red-400';
}
const columns: Column<Position>[] = [
{ key: 'ticker', header: 'Ticker', className: 'font-mono font-semibold text-brand-300' },
{ key: 'quantity', header: 'Qty' },
{ key: 'avg_entry_price', header: 'Entry', render: (r) => <span>{fmtUsd(r.avg_entry_price)}</span> },
{ key: 'current_price', header: 'Current', render: (r) => <span>{fmtUsd(r.current_price)}</span> },
{ key: 'unrealized_pnl', header: 'Unrealized P&L', render: (r) => <span className={pnlColor(r.unrealized_pnl)}>{fmtUsd(r.unrealized_pnl)}</span> },
{ key: 'realized_pnl', header: 'Realized P&L', render: (r) => <span className={pnlColor(r.realized_pnl)}>{fmtUsd(r.realized_pnl)}</span> },
{ key: 'updated_at', header: 'Updated', render: (r) => <span className="text-xs">{new Date(r.updated_at).toLocaleString()}</span> },
];
export function PositionsPage() {
const { data, isLoading } = usePositions();
const { data: companies } = useCompanies();
// Build ticker → company ID lookup
const tickerToId: Record<string, string> = {};
for (const c of companies ?? []) {
tickerToId[c.ticker] = c.id;
}
const posColumns: Column<Position>[] = [
{
key: 'ticker',
header: 'Ticker',
render: (r) => {
const companyId = tickerToId[r.ticker];
return companyId ? (
<Link to="/companies/$id" params={{ id: companyId }} className="font-mono font-semibold text-brand-300 hover:underline">
{r.ticker}
</Link>
) : (
<span className="font-mono font-semibold text-brand-300">{r.ticker}</span>
);
},
},
{ key: 'quantity', header: 'Qty' },
{ key: 'avg_entry_price', header: 'Entry', render: (r) => <span>{fmtUsd(r.avg_entry_price)}</span> },
{ key: 'current_price', header: 'Current', render: (r) => <span>{fmtUsd(r.current_price)}</span> },
{ key: 'unrealized_pnl', header: 'Unrealized P&L', render: (r) => <span className={pnlColor(r.unrealized_pnl)}>{fmtUsd(r.unrealized_pnl)}</span> },
{ key: 'realized_pnl', header: 'Realized P&L', render: (r) => <span className={pnlColor(r.realized_pnl)}>{fmtUsd(r.realized_pnl)}</span> },
{ key: 'updated_at', header: 'Updated', render: (r) => <span className="text-xs">{new Date(r.updated_at).toLocaleString()}</span> },
];
if (isLoading) return <LoadingSpinner />;
@@ -58,7 +79,7 @@ export function PositionsPage() {
<h1 className="mb-4 text-xl font-semibold text-gray-100">Positions</h1>
<DataTable<Position>
data={positions}
columns={columns}
columns={posColumns}
keyField="id"
footerRow={footer}
/>
+21 -4
View File
@@ -1,7 +1,7 @@
import { useState } from 'react';
import { useState, useRef, useEffect } from 'react';
import { useNavigate, Link } from '@tanstack/react-router';
import { useTrends, useDocument } from '../api/hooks';
import { TrendArrow, ConfidenceBar, LoadingSpinner, TickerFilter, Card } from '../components/ui';
import { TrendArrow, ConfidenceBar, LoadingSpinner, Card } from '../components/ui';
import type { TrendSummary } from '../api/hooks';
const WINDOWS = ['intraday', '1d', '7d', '30d', '90d'];
@@ -9,8 +9,17 @@ const WINDOWS = ['intraday', '1d', '7d', '30d', '90d'];
export function TrendsPage() {
const navigate = useNavigate();
const [ticker, setTicker] = useState('');
const [debouncedTicker, setDebouncedTicker] = useState('');
const [window, setWindow] = useState<string | undefined>(undefined);
const { data, isLoading } = useTrends({ ticker: ticker || undefined, window, limit: 100 });
const inputRef = useRef<HTMLInputElement>(null);
// Debounce ticker search — only query after 300ms of no typing
useEffect(() => {
const timer = setTimeout(() => setDebouncedTicker(ticker), 300);
return () => clearTimeout(timer);
}, [ticker]);
const { data, isLoading } = useTrends({ ticker: debouncedTicker || undefined, window, limit: 100 });
if (isLoading) return <LoadingSpinner />;
@@ -19,7 +28,15 @@ export function TrendsPage() {
<div className="mb-4 flex items-center justify-between">
<h1 className="text-xl font-semibold text-gray-100">Trends</h1>
<div className="flex items-center gap-3">
<TickerFilter value={ticker} onChange={setTicker} />
<input
ref={inputRef}
type="text"
placeholder="Ticker…"
value={ticker}
onChange={(e) => setTicker(e.target.value.toUpperCase())}
className="w-24 rounded-md border border-surface-700 bg-surface-900 px-2 py-1 text-xs text-gray-200 placeholder-gray-500 focus:border-brand-500 focus:outline-none"
aria-label="Filter by ticker"
/>
<div className="inline-flex rounded-md border border-surface-700" role="group" aria-label="Window selector">
<button
onClick={() => setWindow(undefined)}
@@ -35,6 +35,8 @@ export function TradingOverview() {
const resume = useResumeTradingEngine();
const updateConfig = useUpdateTradingConfig();
const [selectedTier, setSelectedTier] = useState<string | null>(null);
const [maxPositions, setMaxPositions] = useState<number | null>(null);
const [positionCap, setPositionCap] = useState<number | null>(null);
if (isLoading) return <LoadingSpinner />;
if (!status) return <p className="text-gray-500">No trading status available</p>;
@@ -131,6 +133,68 @@ export function TradingOverview() {
<StatCard label="Portfolio Heat" value={fmtPct(status.portfolio_heat)} />
</div>
{/* Position Limits */}
<Card>
<h2 className="mb-3 text-sm font-medium text-gray-400">Position Limits</h2>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div>
<label htmlFor="max-positions" className="block text-xs text-gray-500 mb-1">
Max Open Positions
</label>
<div className="flex items-center gap-2">
<input
id="max-positions"
type="number"
min={1}
max={50}
value={maxPositions ?? status.max_open_positions ?? 10}
onChange={(e) => setMaxPositions(Number(e.target.value))}
className="w-20 rounded-md border border-surface-700 bg-surface-950 px-2 py-1.5 text-sm text-gray-200 focus:border-brand-500 focus:outline-none"
/>
<button
onClick={() => {
const val = maxPositions ?? status.max_open_positions ?? 10;
updateConfig.mutate({ max_open_positions: val });
}}
disabled={updateConfig.isPending}
className="rounded-md bg-brand-700 px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-600 disabled:opacity-50"
>
Apply
</button>
<span className="text-xs text-gray-500">
Current: {status.open_position_count ?? 0} / {status.max_open_positions ?? 10}
</span>
</div>
</div>
<div>
<label htmlFor="position-cap" className="block text-xs text-gray-500 mb-1">
Absolute Position Cap ($)
</label>
<div className="flex items-center gap-2">
<input
id="position-cap"
type="number"
min={10}
step={10}
value={positionCap ?? status.absolute_position_cap ?? 50}
onChange={(e) => setPositionCap(Number(e.target.value))}
className="w-24 rounded-md border border-surface-700 bg-surface-950 px-2 py-1.5 text-sm text-gray-200 focus:border-brand-500 focus:outline-none"
/>
<button
onClick={() => {
const val = positionCap ?? status.absolute_position_cap ?? 50;
updateConfig.mutate({ absolute_position_cap: val });
}}
disabled={updateConfig.isPending}
className="rounded-md bg-brand-700 px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-600 disabled:opacity-50"
>
Apply
</button>
</div>
</div>
</div>
</Card>
{/* Portfolio Heat Gauge */}
<Card>
<h2 className="mb-2 text-sm font-medium text-gray-400">Portfolio Heat</h2>
+4
View File
@@ -1,8 +1,12 @@
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { configure } from '@testing-library/react';
import { afterEach, afterAll, beforeAll } from 'vitest';
import { server } from './mocks/server';
// CI containers can be slow under parallel builds — increase default waitFor timeout
configure({ asyncUtilTimeout: 5000 });
beforeAll(() => server.listen({ onUnhandledRequest: 'warn' }));
afterEach(() => {
cleanup();
+9 -4
View File
@@ -26,8 +26,7 @@ config:
DEPLOY_STAGE: "beta"
LOG_LEVEL: "DEBUG"
JSON_LOGS: "true"
# Disable actual trading in beta — safety net
TRADING_ENABLED: "false"
TRADING_ENABLED: "true"
# Use same infra services (shared postgres/redis/minio)
POSTGRES_HOST: "postgresql-rw.postgresql-service.svc.cluster.local"
POSTGRES_PORT: "5432"
@@ -42,6 +41,12 @@ config:
BROKER_PROVIDER: "alpaca"
OLLAMA_BASE_URL: "http://192.168.42.254:11434"
OLLAMA_MODEL: "qwen3.6"
VLLM_BASE_URL: "http://192.168.42.254:8000"
VLLM_MODEL: "AxionML/Qwen3.5-9B-NVFP4"
VLLM_TIMEOUT: "120"
VLLM_MAX_RETRIES: "2"
VLLM_TEMPERATURE: "0.7"
VLLM_API_KEY: ""
MARKET_DATA_BASE_URL: "https://api.polygon.io"
PIPELINE_DEFAULT_OFF: "true"
@@ -55,8 +60,8 @@ secrets:
MINIO_SECRET_KEY: "8fG3!v2rJ7$wN@9mLpQ6zXbC4tKdPqW1"
REDIS_PASSWORD: "PSCh4ng3me!"
broker:
BROKER_API_KEY: "PKEQXRJUTQCXJYLB4QOQC2LE6"
BROKER_API_SECRET: "Df1ZKL6d7F83CDM1jaFDh3K4BxQZJY9VoymoFvEaWiij"
BROKER_API_KEY: "PKRTP2PRRNCO3AYRGCK2FGWGMJ"
BROKER_API_SECRET: "dWhCubuyzTGDTPqtV1HXdUGhu8ZQB6EP4oui3GRyDTT"
BROKER_BASE_URL: "https://paper-api.alpaca.markets"
market:
MARKET_DATA_API_KEY: "NPwKtrLvoBxcKt3Byp5PEvuZiBZU_d8E"
+13 -6
View File
@@ -59,7 +59,7 @@ services:
limits: { cpu: 500m, memory: 256Mi }
extractor:
replicas: 1
replicas: 8
pipeline: true
image: extractor
command: "python -m services.extractor.main"
@@ -174,13 +174,19 @@ config:
REDIS_DB: "0"
MINIO_ENDPOINT: "minio.minio-service.svc.cluster.local:80"
MINIO_SECURE: "false"
OLLAMA_BASE_URL: ""
OLLAMA_BASE_URL: "http://10.1.1.12:2701"
OLLAMA_MODEL: "qwen3.5:9b-fast"
OLLAMA_TIMEOUT: "240"
OLLAMA_MAX_RETRIES: "2"
OLLAMA_RETRY_BASE_DELAY: "1.0"
OLLAMA_RETRY_MAX_DELAY: "10.0"
OLLAMA_RETRY_BACKOFF_MULTIPLIER: "2.0"
VLLM_BASE_URL: "http://192.168.42.254:8000"
VLLM_MODEL: "AxionML/Qwen3.5-9B-NVFP4"
VLLM_TIMEOUT: "120"
VLLM_MAX_RETRIES: "2"
VLLM_TEMPERATURE: "0.7"
VLLM_API_KEY: ""
TRINO_HOST: "trino.stonks-oracle.svc.cluster.local"
TRINO_PORT: "8080"
TRINO_CATALOG: "lakehouse"
@@ -215,14 +221,15 @@ config:
TRADING_RISK_TIER: "moderate"
TRADING_ABSOLUTE_POSITION_CAP: "10000.0"
TRADING_MAX_OPEN_POSITIONS: "10"
TZ: "America/Los_Angeles"
## Secrets
secrets:
core:
POSTGRES_PASSWORD: ""
MINIO_ACCESS_KEY: ""
MINIO_SECRET_KEY: ""
REDIS_PASSWORD: ""
POSTGRES_PASSWORD: "St0nks0racl3!"
MINIO_ACCESS_KEY: "AKIA6V7J3N9B5P0D2YQH"
MINIO_SECRET_KEY: "8fG3!v2rJ7$wN@9mLpQ6zXbC4tKdPqW1"
REDIS_PASSWORD: "PSCh4ng3me!"
broker:
BROKER_API_KEY: ""
BROKER_API_SECRET: ""
+7 -7
View File
@@ -7,7 +7,7 @@ CREATE TABLE IF NOT EXISTS ai_agents (
name VARCHAR(100) NOT NULL UNIQUE,
slug VARCHAR(100) NOT NULL UNIQUE,
purpose TEXT NOT NULL DEFAULT '',
model_provider VARCHAR(50) NOT NULL DEFAULT 'ollama',
model_provider VARCHAR(50) NOT NULL DEFAULT 'vllm',
model_name VARCHAR(200) NOT NULL DEFAULT 'qwen3.5:9b',
system_prompt TEXT NOT NULL DEFAULT '',
user_prompt_template TEXT NOT NULL DEFAULT '',
@@ -37,8 +37,8 @@ SELECT * FROM (VALUES
'Document Intelligence Extractor',
'document-extractor',
'Extracts structured intelligence (sentiment, catalysts, impact scores, key facts, risks) from company news, SEC filings, earnings transcripts, and press releases.',
'ollama',
'qwen3.5:9b-fast',
'vllm',
'AxionML/Qwen3.5-9B-NVFP4',
E'You are a financial document analyst. Extract structured data as JSON. Return ONLY a single JSON object. No markdown fences, no explanation, no text before or after the JSON. Every field in the schema is required. Use "other" for catalyst_type if unsure. Keep evidence_spans short (under 20 words each). Keep key_facts to 3-5 items max.',
'document-intel-v2',
'2.0.0',
@@ -48,8 +48,8 @@ SELECT * FROM (VALUES
'Global Event Classifier',
'event-classifier',
'Classifies global/geopolitical news into structured macro events with impact type, severity, affected regions/sectors/commodities, and estimated duration.',
'ollama',
'qwen3.5:9b-fast',
'vllm',
'AxionML/Qwen3.5-9B-NVFP4',
E'You classify MACRO-LEVEL global news into structured event JSON. Return ONLY a single JSON object. No markdown, no explanation. Every field is required. Keep key_facts to 3-5 items. Keep summary under 3 sentences.\n\nCRITICAL: Only classify articles about MACRO events that affect entire markets, sectors, or economies. Examples: trade wars, interest rate changes, commodity supply disruptions, regulatory changes, geopolitical conflicts, natural disasters.\n\nDO NOT classify as macro events: individual company earnings, lawsuits against a single company, single-company management changes, individual stock analysis, company-specific debt or bankruptcy, product launches by one company. For these, set severity to "low", confidence below 0.3, and leave affected_regions, affected_sectors, and affected_commodities as empty arrays.',
'event-classification-v1',
'1.0.0',
@@ -59,8 +59,8 @@ SELECT * FROM (VALUES
'Thesis Rewriter',
'thesis-rewriter',
'Rewrites deterministic trade thesis summaries into clear, professional analyst prose. Optional layer — system falls back to deterministic thesis if this fails.',
'ollama',
'qwen3.5:9b-fast',
'vllm',
'AxionML/Qwen3.5-9B-NVFP4',
E'You are a concise financial analyst. You rewrite structured trade thesis summaries into clear, professional prose suitable for an internal research note.\n\nSTRICT RULES:\n1. Do NOT add any information that is not present in the input.\n2. Do NOT fabricate numbers, dates, company names, or analyst opinions.\n3. Keep the rewrite under 150 words.\n4. Preserve all factual claims, risk notes, and evidence counts from the input.\n5. Use a neutral, professional tone. Avoid hype or marketing language.\n6. Return ONLY the rewritten thesis text. No JSON, no markdown, no commentary.',
'thesis-rewrite-v1',
'1.0.0',
+8 -7
View File
@@ -1,22 +1,23 @@
-- Sync ai_agents system_prompt and model_name to match code defaults.
-- The original 026 seed used abbreviated prompts and the base model name;
-- this migration brings them in line with the authoritative prompts defined
-- in the Python service code and the actual deployed model tag.
-- Sync ai_agents system_prompt to match code defaults.
-- The original 026 seed used abbreviated prompts; this migration brings
-- them in line with the authoritative prompts defined in the Python
-- service code.
--
-- NOTE: model_name and model_provider are NOT overwritten here.
-- They are configured per-environment via the API or direct DB update
-- and should not be reset by migrations.
UPDATE ai_agents
SET system_prompt = E'You are a financial document analyst. Extract structured data as JSON. Return ONLY a single JSON object. No markdown fences, no explanation, no text before or after the JSON. Every field in the schema is required. Use "other" for catalyst_type if unsure. Keep evidence_spans short (under 20 words each). Keep key_facts to 3-5 items max.',
model_name = 'qwen3.5:9b-fast',
updated_at = NOW()
WHERE slug = 'document-extractor';
UPDATE ai_agents
SET system_prompt = E'You classify MACRO-LEVEL global news into structured event JSON. Return ONLY a single JSON object. No markdown, no explanation. Every field is required. Keep key_facts to 3-5 items. Keep summary under 3 sentences.\n\nCRITICAL: Only classify articles about MACRO events that affect entire markets, sectors, or economies. Examples: trade wars, interest rate changes, commodity supply disruptions, regulatory changes, geopolitical conflicts, natural disasters.\n\nDO NOT classify as macro events: individual company earnings, lawsuits against a single company, single-company management changes, individual stock analysis, company-specific debt or bankruptcy, product launches by one company. For these, set severity to "low", confidence below 0.3, and leave affected_regions, affected_sectors, and affected_commodities as empty arrays.',
model_name = 'qwen3.5:9b-fast',
updated_at = NOW()
WHERE slug = 'event-classifier';
UPDATE ai_agents
SET system_prompt = E'You are a concise financial analyst. You rewrite structured trade thesis summaries into clear, professional prose suitable for an internal research note.\n\nSTRICT RULES:\n1. Do NOT add any information that is not present in the input.\n2. Do NOT fabricate numbers, dates, company names, or analyst opinions.\n3. Keep the rewrite under 150 words.\n4. Preserve all factual claims, risk notes, and evidence counts from the input.\n5. Use a neutral, professional tone. Avoid hype or marketing language.\n6. Return ONLY the rewritten thesis text. No JSON, no markdown, no commentary.',
model_name = 'qwen3.5:9b-fast',
updated_at = NOW()
WHERE slug = 'thesis-rewriter';
@@ -0,0 +1,13 @@
-- Fix agent default model_provider and model_name to match production config.
-- The original migration 026 seeded with 'ollama'/'qwen3.5:9b-fast' but production
-- uses vLLM. This migration updates agents that still have the old defaults,
-- preserving any user customizations (only updates if model_name matches the old default).
UPDATE ai_agents
SET model_provider = 'vllm',
model_name = 'AxionML/Qwen3.5-9B-NVFP4',
max_tokens = 2048,
updated_at = NOW()
WHERE slug IN ('document-extractor', 'event-classifier', 'thesis-rewriter')
AND source = 'system'
AND model_name = 'qwen3.5:9b-fast';
@@ -0,0 +1,15 @@
-- Fix max_tokens default: 32768 is the full context window, not a reasonable
-- output limit. vLLM rejects requests where max_tokens >= context_window
-- because there's no room left for the input prompt.
--
-- Change the column default to 4096 (sufficient for structured JSON extraction
-- output) and update any existing rows still at the old default.
ALTER TABLE ai_agents ALTER COLUMN max_tokens SET DEFAULT 4096;
ALTER TABLE agent_variants ALTER COLUMN max_tokens SET DEFAULT 4096;
UPDATE ai_agents SET max_tokens = 4096, updated_at = NOW()
WHERE max_tokens = 32768;
UPDATE agent_variants SET max_tokens = 4096
WHERE max_tokens = 32768;
@@ -0,0 +1,12 @@
-- Seed a default risk_configs row with all signal layers explicitly enabled.
-- This ensures fresh deployments have macro and competitive layers active
-- without requiring manual API calls or DB patches.
-- Idempotent: skips if an active config already exists.
INSERT INTO risk_configs (name, trading_mode, config, active)
SELECT 'default', 'paper',
'{"macro_enabled": true, "competitive_enabled": true}'::jsonb,
TRUE
WHERE NOT EXISTS (
SELECT 1 FROM risk_configs WHERE active = TRUE
);
@@ -0,0 +1,16 @@
-- Stop hardcoding agent model_name in migrations.
--
-- Migration 029 previously forced model_name='qwen3.5:9b-fast' on every
-- deploy, overwriting per-environment model configuration. That migration
-- has been fixed to only sync system_prompt (not model_name).
--
-- This migration updates agents still on the old ollama provider/model
-- to use vllm with the default VLLM model. Agents already configured
-- with a different model (e.g. via the API) are left untouched.
UPDATE ai_agents
SET model_provider = 'vllm',
model_name = 'AxionML/Qwen3.5-9B-NVFP4',
updated_at = NOW()
WHERE model_name IN ('qwen3.5:9b-fast', 'qwen3.5:9b')
AND source = 'system';
+18
View File
@@ -0,0 +1,18 @@
-- Source accuracy tracking table for historical prediction accuracy per source.
--
-- Stores per-source accuracy metrics (fraction of correct directional calls)
-- used by the probabilistic scoring pipeline to weight source credibility.
-- See Requirement 4.5: source accuracy metrics stored with source identifier,
-- accuracy ratio, sample count, and last updated timestamp.
CREATE TABLE IF NOT EXISTS source_accuracy (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
source_id VARCHAR(200) NOT NULL,
accuracy_ratio FLOAT NOT NULL DEFAULT 0.5,
sample_count INTEGER NOT NULL DEFAULT 0,
last_updated TIMESTAMPTZ NOT NULL DEFAULT NOW(),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE(source_id)
);
CREATE INDEX IF NOT EXISTS idx_source_accuracy_source ON source_accuracy(source_id);
+66
View File
@@ -0,0 +1,66 @@
# Gitea deployment with NFS-backed PVC
# Replaces the old hostPath volume with a PersistentVolumeClaim
# bound to the gitea-data-nfs PV (see pvs/gitea-pv.yaml).
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: gitea-data
namespace: git-server
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
volumeName: gitea-data-nfs
storageClassName: ""
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: gitea
namespace: git-server
spec:
replicas: 1
selector:
matchLabels:
app: gitea
template:
metadata:
labels:
app: gitea
spec:
containers:
- name: gitea
image: gitea/gitea:latest
imagePullPolicy: Always
ports:
- containerPort: 3000
- containerPort: 22
volumeMounts:
- mountPath: /data
name: gitea-data
volumes:
- name: gitea-data
persistentVolumeClaim:
claimName: gitea-data
---
apiVersion: v1
kind: Service
metadata:
name: gitea-service
namespace: git-server
spec:
type: NodePort
selector:
app: gitea
ports:
- name: http
port: 3000
targetPort: 3000
nodePort: 30300
- name: ssh
port: 22
targetPort: 22
nodePort: 30022
+2 -2
View File
@@ -85,10 +85,10 @@ elif [ "$HTTP_CODE" = "404" ]; then
--data-urlencode "repo_root_path=/data/git/repositories" \
--data-urlencode "lfs_root_path=/data/git/lfs" \
--data-urlencode "run_user=git" \
--data-urlencode "domain=gitea-service.git-server.svc.cluster.local" \
--data-urlencode "domain=git.celestium.life" \
--data-urlencode "ssh_port=22" \
--data-urlencode "http_port=3000" \
--data-urlencode "app_url=http://gitea-service.git-server.svc.cluster.local:3000/" \
--data-urlencode "app_url=https://git.celestium.life/" \
--data-urlencode "log_root_path=/data/gitea/log" \
--data-urlencode "admin_name=${GITEA_ADMIN_USER}" \
--data-urlencode "admin_passwd=${GITEA_ADMIN_PASSWORD}" \
+19
View File
@@ -0,0 +1,19 @@
# Gitea NFS PersistentVolume
# NFS path: nfs://192.168.42.8:/volume1/Kubernetes/gitea
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: gitea-data-nfs
labels:
app: gitea
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: ""
nfs:
server: 192.168.42.8
path: /volume1/Kubernetes/gitea
+4 -1
View File
@@ -13,4 +13,7 @@ spec:
storageClassName: ""
nfs:
server: 192.168.42.8
path: /volume1/Kubernetes/pipelines/woodpecker
path: /volume1/Kubernetes/woodpecker
claimRef:
namespace: woodpecker
name: data-woodpecker-server-0
+11
View File
@@ -53,12 +53,23 @@ echo ""
# -------------------------------------------------------
echo "--- Step 3: Applying NFS PersistentVolumes ---"
kubectl apply -f pvs/argocd-pv.yaml
kubectl apply -f pvs/gitea-pv.yaml
kubectl apply -f pvs/kargo-pv.yaml
kubectl apply -f pvs/woodpecker-pv.yaml
kubectl apply -f pvs/harbor-pv.yaml
echo " ✓ PVs applied"
echo ""
# -------------------------------------------------------
# 3a. Apply Gitea deployment (NFS-backed)
# -------------------------------------------------------
echo "--- Step 3a: Applying Gitea deployment ---"
kubectl create namespace git-server --dry-run=client -o yaml | kubectl apply -f -
kubectl apply -f gitea/deployment.yaml
kubectl rollout status deployment/gitea -n git-server --timeout=60s
echo " ✓ Gitea deployed with NFS storage"
echo ""
# -------------------------------------------------------
# 3b. Install Harbor container registry
# -------------------------------------------------------
@@ -0,0 +1,63 @@
# CronJob + RBAC to clean up orphaned Woodpecker step secrets (wp-*-step-secret)
# These accumulate when builds fail or are cancelled before cleanup runs.
# Runs every 6 hours. TTL auto-deletes completed Job pods after 5 minutes.
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: wp-secret-cleanup
namespace: woodpecker
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["list", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: wp-secret-cleanup
namespace: woodpecker
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: wp-secret-cleanup
subjects:
- kind: ServiceAccount
name: default
namespace: woodpecker
---
apiVersion: batch/v1
kind: CronJob
metadata:
name: cleanup-wp-step-secrets
namespace: woodpecker
spec:
schedule: "0 */6 * * *"
successfulJobsHistoryLimit: 1
failedJobsHistoryLimit: 1
jobTemplate:
spec:
ttlSecondsAfterFinished: 300
template:
spec:
serviceAccountName: default
restartPolicy: Never
containers:
- name: cleanup
image: registry.celestium.life/dockerhub-cache/bitnami/kubectl:latest
command:
- /bin/sh
- -c
- |
echo 'Cleaning up orphaned Woodpecker step secrets...'
SECRETS=$(kubectl get secret -n woodpecker -o name | grep 'wp-.*step-secret')
COUNT=$(echo "$SECRETS" | grep -c 'step-secret' || true)
echo "Found $COUNT orphaned step secrets"
if [ "$COUNT" -gt 0 ]; then
echo "$SECRETS" | while read s; do
kubectl delete -n woodpecker "$s" 2>/dev/null || true
done
echo "Cleanup complete"
else
echo "Nothing to clean"
fi
+3 -3
View File
@@ -13,9 +13,9 @@ server:
WOODPECKER_SERVER_ADDR: "0.0.0.0:8000"
WOODPECKER_GRPC_ADDR: "0.0.0.0:9000"
WOODPECKER_GITEA: "true"
WOODPECKER_GITEA_URL: "http://gitea-service.git-server.svc.cluster.local:3000"
WOODPECKER_GITEA_CLIENT: "8fb7fc0f-98f6-42b5-b066-6cc4d745de4f"
WOODPECKER_GITEA_SECRET: "gto_izanujbxlcxzc23znan56m3uie6s4ta2lgvro2yhgmuwvw3vutkq"
WOODPECKER_GITEA_URL: "https://git.celestium.life"
WOODPECKER_GITEA_CLIENT: "5f40e5f2-0153-458e-be5a-2ed5fd1b9054"
WOODPECKER_GITEA_SECRET: "gto_h3rindnfegcurodm2vvujm7gzr6t5ly4rs2eto2wg57epwoi2x6q"
WOODPECKER_AGENT_SECRET: "01eede973f522dbea9c1f09afc020ed0934a6f946d5832be5fecacb0da04ce23"
WOODPECKER_ADMIN: "admin"
WOODPECKER_PLUGINS_PRIVILEGED: "woodpeckerci/plugin-docker-buildx"
+74 -3
View File
@@ -52,6 +52,7 @@ from services.risk.engine import (
AccountRiskState,
PortfolioRiskConfig,
ProposedOrder,
clamp_order_to_position_limits,
evaluate_order,
)
from services.shared.audit import (
@@ -66,6 +67,7 @@ from services.shared.config import load_config
from services.shared.db import get_pg_pool, get_redis
from services.shared.logging import setup_logging
from services.shared.metrics import (
ORDERS_CLAMPED,
ORDERS_DUPLICATES_PREVENTED,
ORDERS_FILLED,
ORDERS_REJECTED,
@@ -74,7 +76,7 @@ from services.shared.metrics import (
RISK_CHECK_FAILURES,
RISK_EVALUATIONS_TOTAL,
)
from services.shared.redis_keys import QUEUE_BROKER, queue_key
from services.shared.redis_keys import QUEUE_BROKER, is_pipeline_enabled, queue_key
logger = logging.getLogger("broker_service")
@@ -288,6 +290,25 @@ async def load_risk_config(pool: asyncpg.Pool) -> PortfolioRiskConfig:
return PortfolioRiskConfig()
async def _estimate_share_price(
adapter: AlpacaBrokerAdapter,
ticker: str,
) -> float:
"""Estimate the current per-share price for a ticker.
Checks existing Alpaca positions first (free, no API call).
Returns 0.0 if no price can be determined.
"""
try:
positions = await adapter.get_positions()
for pos in positions:
if pos.ticker == ticker and pos.current_price > 0:
return pos.current_price
except Exception as e:
logger.debug("Could not fetch positions for price estimate: %s", e)
return 0.0
async def load_account_risk_state(
pool: asyncpg.Pool,
adapter: AlpacaBrokerAdapter,
@@ -407,10 +428,16 @@ async def sync_positions(
account_uuid: str,
minio_client: Any | None = None,
) -> None:
"""Sync current positions from Alpaca to PostgreSQL and publish to lake."""
"""Sync current positions from Alpaca to PostgreSQL and publish to lake.
Performs a full reconciliation: upserts positions that Alpaca reports,
then removes any DB positions that Alpaca no longer holds (e.g. after
a paper reset or full liquidation).
"""
now = datetime.now(timezone.utc)
try:
positions = await adapter.get_positions()
broker_tickers = {pos.ticker for pos in positions}
async with pool.acquire() as conn:
for pos in positions:
await conn.execute(
@@ -423,7 +450,20 @@ async def sync_positions(
pos.unrealized_pnl,
now,
)
logger.info("Synced %d positions from Alpaca", len(positions))
# Remove positions that the broker no longer reports (closed/liquidated)
if broker_tickers:
await conn.execute(
"DELETE FROM positions WHERE broker_account_id = $1::uuid AND ticker != ALL($2::varchar[])",
account_uuid,
list(broker_tickers),
)
else:
# Broker reports zero positions — clear all local positions for this account
await conn.execute(
"DELETE FROM positions WHERE broker_account_id = $1::uuid",
account_uuid,
)
logger.info("Synced %d positions from Alpaca (reconciled)", len(positions))
POSITIONS_SYNCED.inc()
# Publish positions snapshot to analytical lake
@@ -534,6 +574,34 @@ async def process_order_job(
risk_config = await load_risk_config(pool)
risk_state = await load_account_risk_state(pool, adapter, account_uuid)
proposed = build_proposed_order(job)
# If estimated_value is missing, derive it from Alpaca positions or
# a fresh quote so that position-limit clamping can work.
if proposed.estimated_value <= 0 and proposed.quantity > 0:
price_per_share = await _estimate_share_price(adapter, proposed.ticker)
if price_per_share > 0:
proposed = proposed.model_copy(update={
"estimated_value": proposed.quantity * price_per_share,
})
job["estimated_value"] = proposed.estimated_value
# Auto-clamp buy orders to fit within position limits instead of
# hard-rejecting. If the clamped quantity is zero the normal risk
# evaluation will still reject the order with a clear reason.
original_qty = proposed.quantity
proposed = clamp_order_to_position_limits(proposed, risk_config, risk_state)
if proposed.quantity != original_qty:
logger.info(
"Order for %s clamped from %.0f to %.0f shares "
"(value %.2f%.2f) to fit position limits",
ticker, original_qty, proposed.quantity,
float(job.get("estimated_value", 0)), proposed.estimated_value,
)
ORDERS_CLAMPED.inc()
# Update the job dict so build_order_request picks up the clamped qty
job["quantity"] = proposed.quantity
job["estimated_value"] = proposed.estimated_value
evaluation = evaluate_order(proposed, risk_config, risk_state)
risk_eval_dict = {
@@ -874,6 +942,9 @@ async def main() -> None:
try:
while True:
if not await is_pipeline_enabled(rds):
await asyncio.sleep(2)
continue
result = await rds.lpop(queue)
raw = str(result) if result else None
if raw:
+4 -4
View File
@@ -135,11 +135,11 @@ class PolygonMarketAdapter(MarketDataAdapter):
if config.get("limit"):
params["limit"] = str(config["limit"])
elif endpoint_key == "intraday_bars":
# Intraday: fetch hourly bars for today
# Intraday: fetch 15-minute bars for today
from datetime import date as date_cls
today = date_cls.today().isoformat()
multiplier = str(config.get("multiplier", 1))
timespan = config.get("timespan", "hour")
multiplier = str(config.get("multiplier", 15))
timespan = config.get("timespan", "minute")
path = self.INTRADAY_BARS.format(
ticker=ticker,
multiplier=multiplier,
@@ -149,7 +149,7 @@ class PolygonMarketAdapter(MarketDataAdapter):
)
params["adjusted"] = str(config.get("adjusted", True)).lower()
params["sort"] = "asc"
params["limit"] = str(config.get("limit", 50))
params["limit"] = str(config.get("limit", 100))
elif endpoint_key == "grouped_daily":
# Grouped daily: returns bars for ALL tickers for a given date
target_date = config.get("date", "")
+127
View File
@@ -0,0 +1,127 @@
"""Bayesian accumulator for probabilistic sentiment aggregation.
Accumulates weighted signals into a Bayesian posterior using
log-likelihood accumulation, Beta distribution parameters, and
Shannon entropy for mixed-signal detection.
Requirements: 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 9.1, 9.7
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from services.aggregation.scoring import WeightedSignal
@dataclass(frozen=True)
class BayesianPosterior:
"""Bayesian posterior state from signal accumulation."""
p_bull: float # σ(L_t), bullish probability [0, 1]
alpha: float # Beta distribution α parameter (≥ 1.0)
beta: float # Beta distribution β parameter (≥ 1.0)
log_likelihood: float # Raw log-likelihood accumulation L_t
bayesian_confidence: float # 1 - 4αβ/(α+β)², [0, 1]
entropy: float # Shannon entropy H, [0, 1]
signal_count: int # Number of signals processed
# Uninformative prior (no evidence)
PRIOR = BayesianPosterior(
p_bull=0.5,
alpha=1.0,
beta=1.0,
log_likelihood=0.0,
bayesian_confidence=0.0,
entropy=1.0,
signal_count=0,
)
def compute_entropy(p_bull: float) -> float:
"""Shannon entropy H = -p·log₂(p) - (1-p)·log₂(1-p).
Returns value in [0, 1]. Maximum at p=0.5, zero at p=0 or p=1.
Handles edge cases p≤0 and p≥1 by returning 0.0.
"""
if p_bull <= 0.0 or p_bull >= 1.0:
return 0.0
q = 1.0 - p_bull
return -(p_bull * math.log2(p_bull) + q * math.log2(q))
def compute_bayesian_posterior(
signals: list[WeightedSignal],
) -> BayesianPosterior:
"""Accumulate weighted signals into a Bayesian posterior.
Computes:
- Log-likelihood: L_t = Σ(w_i · s_i)
- Bullish probability: P_bull = σ(L_t)
- Beta posterior: α = 1 + W_bull, β = 1 + W_bear
- Bayesian confidence: C = 1 - 4αβ/(α+β)²
- Shannon entropy: H = -p·log₂(p) - (1-p)·log₂(1-p)
Returns PRIOR for empty signal lists.
Skips signals with NaN weight or sentiment.
"""
if not signals:
return PRIOR
log_likelihood = 0.0
w_bull = 0.0
w_bear = 0.0
count = 0
for sig in signals:
combined = sig.weight.combined
sentiment = sig.sentiment_value
# Skip signals with NaN weight or sentiment
if math.isnan(combined) or math.isnan(sentiment):
continue
log_likelihood += combined * sentiment
if sentiment > 0.0:
w_bull += combined
elif sentiment < 0.0:
w_bear += combined
count += 1
if count == 0:
return PRIOR
# P_bull via sigmoid: σ(L_t) = 1 / (1 + exp(-L_t))
# Guard against overflow in exp for very large |L_t|
if log_likelihood > 500.0:
p_bull = 1.0
elif log_likelihood < -500.0:
p_bull = 0.0
else:
p_bull = 1.0 / (1.0 + math.exp(-log_likelihood))
# Beta posterior parameters
alpha = 1.0 + w_bull
beta_param = 1.0 + w_bear
# Bayesian confidence: C = 1 - 4αβ/(α+β)²
ab_sum = alpha + beta_param
bayesian_confidence = 1.0 - (4.0 * alpha * beta_param) / (ab_sum * ab_sum)
# Clamp to [0, 1] to guard against floating-point rounding
bayesian_confidence = max(0.0, min(1.0, bayesian_confidence))
# Shannon entropy
entropy = compute_entropy(p_bull)
return BayesianPosterior(
p_bull=p_bull,
alpha=alpha,
beta=beta_param,
log_likelihood=log_likelihood,
bayesian_confidence=bayesian_confidence,
entropy=entropy,
signal_count=count,
)
+71 -2
View File
@@ -4,10 +4,11 @@ Analyses weighted signals to detect and represent disagreement explicitly,
rather than collapsing contradictory evidence into a single unsupported
conclusion.
Requirements: 6.4, 6.5
Requirements: 6.4, 6.5, 15.115.7
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from services.aggregation.scoring import WeightedSignal
@@ -35,6 +36,9 @@ class ContradictionResult:
def detect_contradictions(
signals: list[WeightedSignal],
catalyst_entries: list[CatalystEntry] | None = None,
*,
probabilistic: bool = False,
w_threshold: float = 5.0,
) -> ContradictionResult:
"""Run contradiction detection across multiple dimensions.
@@ -42,6 +46,16 @@ def detect_contradictions(
1. Sentiment disagreement — the core positive-vs-negative split
2. Catalyst disagreement — same catalyst type with opposing sentiment
When ``probabilistic`` is True, the overall score uses weighted
disagreement entropy (Req 15.115.7) instead of the minority/majority
ratio. When False, the existing ratio formula is preserved exactly.
Args:
signals: Weighted signals to analyse.
catalyst_entries: Optional catalyst metadata for per-catalyst analysis.
probabilistic: Use entropy-based scoring when True.
w_threshold: Evidence mass threshold for entropy weighting (default 5.0).
Returns a ContradictionResult with an overall score and per-dimension
disagreement details.
"""
@@ -55,7 +69,10 @@ def detect_contradictions(
catalyst_details = _detect_catalyst_disagreement(signals, catalyst_entries)
details.extend(catalyst_details)
score = _compute_overall_score(signals)
if probabilistic:
score = _compute_entropy_score(signals, w_threshold)
else:
score = _compute_overall_score(signals)
return ContradictionResult(score=score, details=details)
@@ -82,6 +99,58 @@ def _compute_overall_score(signals: list[WeightedSignal]) -> float:
return round(minority / total, 4)
def _compute_entropy_score(
signals: list[WeightedSignal],
w_threshold: float = 5.0,
) -> float:
"""Weighted disagreement entropy — probabilistic contradiction score.
Computes Shannon entropy over the positive/negative weight distribution,
weighted by evidence mass relative to a configurable threshold.
Formula:
f_pos = W_pos / (W_pos + W_neg)
f_neg = 1 - f_pos
H = -f_pos·log₂(f_pos) - f_neg·log₂(f_neg) (in [0, 1])
score = H · min(1.0, (W_pos + W_neg) / W_threshold)
Returns 0.0 when only one direction exists (no disagreement).
Requirements: 15.115.7
"""
if not signals:
return 0.0
pos_weight = 0.0
neg_weight = 0.0
for sig in signals:
w = sig.weight.combined * sig.impact_score
if sig.sentiment_value > 0:
pos_weight += w
elif sig.sentiment_value < 0:
neg_weight += w
# No disagreement when only one direction exists (Req 15.5)
if pos_weight <= 0.0 or neg_weight <= 0.0:
return 0.0
total = pos_weight + neg_weight
# Compute weight fractions (Req 15.2)
f_pos = pos_weight / total
f_neg = neg_weight / total # = 1 - f_pos
# Shannon entropy H = -f_pos·log₂(f_pos) - f_neg·log₂(f_neg) (Req 15.3)
# Guard against log₂(0) — already handled by the early return above
h_contradiction = -f_pos * math.log2(f_pos) - f_neg * math.log2(f_neg)
# Weight by evidence mass (Req 15.4)
evidence_factor = min(1.0, total / w_threshold) if w_threshold > 0.0 else 1.0
score = h_contradiction * evidence_factor
return round(score, 4)
def _detect_sentiment_disagreement(
signals: list[WeightedSignal],
) -> DisagreementDetail | None:
+233 -16
View File
@@ -283,27 +283,82 @@ def _determine_impact_direction(
# ---------------------------------------------------------------------------
def _compute_multiplicative_exposure(
geo_overlap: float,
supply_overlap: float,
commodity_overlap: float,
sector_match: float,
) -> float:
"""Compute multiplicative compounding exposure.
Formula: 1 - Π_k(1 - w_k · O_k)
Multi-dimensional exposure compounds — a company exposed across
multiple dimensions receives higher impact than simple addition.
Returns a value in [0, ~0.724] (max when all overlaps are 1.0).
Requirements: 10.1, 10.4, 10.7
"""
product = (
(1.0 - GEO_WEIGHT * geo_overlap)
* (1.0 - SUPPLY_WEIGHT * supply_overlap)
* (1.0 - COMMODITY_WEIGHT * commodity_overlap)
* (1.0 - SECTOR_WEIGHT * sector_match)
)
return 1.0 - product
def _compute_linear_exposure(
geo_overlap: float,
supply_overlap: float,
commodity_overlap: float,
sector_match: float,
) -> float:
"""Compute linear weighted-sum exposure (original heuristic formula).
Formula: w_geo·O_geo + w_supply·O_supply + w_commodity·O_commodity + w_sector·O_sector
Returns a value in [0, 1].
"""
return (
GEO_WEIGHT * geo_overlap
+ SUPPLY_WEIGHT * supply_overlap
+ COMMODITY_WEIGHT * commodity_overlap
+ SECTOR_WEIGHT * sector_match
)
def compute_macro_impact(
event: GlobalEvent,
profile: ExposureProfileSchema,
*,
probabilistic: bool = False,
) -> MacroImpactRecord:
"""Compute the macro impact of a global event on a company.
Scoring formula:
When ``probabilistic=False`` (default), uses the linear weighted-sum:
raw_score = severity_weight * (
0.35 * geographic_overlap +
0.25 * supply_chain_overlap +
0.25 * commodity_overlap +
0.15 * sector_match
)
final_score = apply_resilience_modifier(raw_score, tier, is_international)
When ``probabilistic=True``, uses multiplicative compounding exposure:
raw_score = severity_weight * (1 - Π_k(1 - w_k · O_k))
In both modes, the resilience modifier is applied after the raw score.
Args:
event: The classified global event.
profile: The company's exposure profile.
probabilistic: Use multiplicative formula when True.
Returns:
A MacroImpactRecord with the computed score and metadata.
Requirements: 10.1, 10.2, 10.3, 10.4, 10.5, 10.6
"""
now = datetime.now(timezone.utc)
@@ -360,13 +415,16 @@ def compute_macro_impact(
# Severity weight
severity_weight = SEVERITY_WEIGHTS.get(event.severity, 0.25)
# Raw score
raw_score = severity_weight * (
GEO_WEIGHT * geo_overlap
+ SUPPLY_WEIGHT * supply_overlap
+ COMMODITY_WEIGHT * commodity_overlap
+ SECTOR_WEIGHT * sector_match
)
# Raw score: multiplicative or linear depending on mode
if probabilistic:
exposure = _compute_multiplicative_exposure(
geo_overlap, supply_overlap, commodity_overlap, sector_match,
)
else:
exposure = _compute_linear_exposure(
geo_overlap, supply_overlap, commodity_overlap, sector_match,
)
raw_score = severity_weight * exposure
# Determine if event is international (affects multiple regions)
is_international = len(event.affected_regions) > 1
@@ -406,19 +464,27 @@ def compute_macro_impact_with_sector(
event: GlobalEvent,
profile: ExposureProfileSchema,
company_sector: str = "",
*,
probabilistic: bool = False,
) -> MacroImpactRecord:
"""Compute macro impact with explicit sector matching.
Like compute_macro_impact but accepts a company_sector parameter
for proper sector_match computation.
When ``probabilistic=True``, uses multiplicative compounding exposure.
When ``probabilistic=False``, uses the original linear weighted sum.
Args:
event: The classified global event.
profile: The company's exposure profile.
company_sector: The company's GICS sector name.
probabilistic: Use multiplicative formula when True.
Returns:
A MacroImpactRecord with the computed score and metadata.
Requirements: 10.1, 10.2, 10.3, 10.4, 10.5, 10.6
"""
now = datetime.now(timezone.utc)
@@ -472,13 +538,16 @@ def compute_macro_impact_with_sector(
# Severity weight
severity_weight = SEVERITY_WEIGHTS.get(event.severity, 0.25)
# Raw score
raw_score = severity_weight * (
GEO_WEIGHT * geo_overlap
+ SUPPLY_WEIGHT * supply_overlap
+ COMMODITY_WEIGHT * commodity_overlap
+ SECTOR_WEIGHT * sector_match
)
# Raw score: multiplicative or linear depending on mode
if probabilistic:
exposure = _compute_multiplicative_exposure(
geo_overlap, supply_overlap, commodity_overlap, sector_match,
)
else:
exposure = _compute_linear_exposure(
geo_overlap, supply_overlap, commodity_overlap, sector_match,
)
raw_score = severity_weight * exposure
# International check
is_international = len(event.affected_regions) > 1
@@ -588,6 +657,154 @@ def _infer_commodities(sector: str, industry: str) -> list[str]:
return sector_commodities.get(sector, [])
# ---------------------------------------------------------------------------
# Conditional macro signal integration (Requirements: 11.111.5)
# ---------------------------------------------------------------------------
def compute_conditional_macro_modifier(
company_strength: float,
company_direction: str,
macro_impact: float,
macro_direction: str,
) -> float:
"""Compute the multiplicative macro modifier for conditional integration.
When both company and macro signals exist, macro acts as a modifier:
S_adjusted = S_company · clamp(1 + M_macro · sign_alignment, 0.5, 1.5)
sign_alignment is +1 when macro and company agree in direction,
-1 when they disagree.
Args:
company_strength: The company-level signal strength (absolute).
company_direction: Company trend direction (bullish/bearish/neutral/mixed).
macro_impact: Normalized macro impact score in [0, 1].
macro_direction: Macro impact direction (positive/negative/mixed/neutral).
Returns:
The multiplicative modifier in [0.5, 1.5].
Requirements: 11.1, 11.2
"""
# Determine sign alignment between company and macro directions
_DIRECTION_SIGN = {
"bullish": 1,
"positive": 1,
"bearish": -1,
"negative": -1,
}
company_sign = _DIRECTION_SIGN.get(company_direction, 0)
macro_sign = _DIRECTION_SIGN.get(macro_direction, 0)
if company_sign == 0 or macro_sign == 0:
# Neutral or mixed directions — no alignment signal
sign_alignment = 0.0
elif company_sign == macro_sign:
sign_alignment = 1.0
else:
sign_alignment = -1.0
raw_modifier = 1.0 + macro_impact * sign_alignment
return max(0.5, min(1.5, raw_modifier))
def integrate_macro_signals(
company_signals: list,
macro_signals: list,
company_direction: str,
macro_impacts: list,
ticker: str = "",
*,
probabilistic: bool = False,
macro_signal_weight: float = 0.3,
) -> tuple[list, float]:
"""Integrate macro signals with company signals.
When ``probabilistic=True``:
- Both exist: apply macro as multiplicative modifier on company signals
- Only macro: fall back to additive behavior with weight 0.3
- Only company: use modifier = 1.0 (no change)
When ``probabilistic=False``:
- Preserve current additive merge behavior (concatenate lists)
Args:
company_signals: WeightedSignal list from company layer.
macro_signals: WeightedSignal list from macro layer.
company_direction: Derived company trend direction string.
macro_impacts: List of MacroImpactRecord or similar with
macro_impact_score and impact_direction attributes.
ticker: Ticker symbol for logging.
probabilistic: Use conditional modifier when True.
macro_signal_weight: Weight for macro-only fallback (default 0.3).
Returns:
Tuple of (merged_signals, macro_modifier_applied).
macro_modifier_applied is 1.0 when no modifier was used.
Requirements: 11.1, 11.2, 11.3, 11.4, 11.5
"""
if not probabilistic:
# Heuristic mode: simple additive merge (current behavior)
merged = list(company_signals) + list(macro_signals)
return merged, 1.0
has_company = len(company_signals) > 0
has_macro = len(macro_signals) > 0
if has_company and has_macro:
# Compute average macro impact and dominant direction
avg_macro_impact = 0.0
direction_counts: dict[str, float] = {}
for mir in macro_impacts:
score = getattr(mir, "macro_impact_score", 0.0)
direction = getattr(mir, "impact_direction", "neutral")
avg_macro_impact += score
direction_counts[direction] = direction_counts.get(direction, 0.0) + score
if macro_impacts:
avg_macro_impact /= len(macro_impacts)
# Dominant macro direction by total impact weight
macro_direction = max(direction_counts, key=direction_counts.get) if direction_counts else "neutral"
modifier = compute_conditional_macro_modifier(
company_strength=0.0, # not used in current formula
company_direction=company_direction,
macro_impact=avg_macro_impact,
macro_direction=macro_direction,
)
logger.info(
"Macro modifier for %s: %.4f (avg_impact=%.4f, macro_dir=%s, company_dir=%s)",
ticker, modifier, avg_macro_impact, macro_direction, company_direction,
)
# Apply modifier to company signals by scaling their impact scores
# We create modified copies rather than mutating originals
from copy import copy
modified_signals = []
for sig in company_signals:
new_sig = copy(sig)
new_sig.impact_score = sig.impact_score * modifier
modified_signals.append(new_sig)
return modified_signals, modifier
if has_macro and not has_company:
# Macro-only fallback: additive behavior with weight 0.3 (Req 11.3)
logger.info(
"Macro-only fallback for %s: using additive merge with weight %.2f",
ticker, macro_signal_weight,
)
return list(macro_signals), 1.0
# Company-only: no modification (Req 11.4)
logger.info("Company-only signals for %s: macro modifier=1.0", ticker)
return list(company_signals), 1.0
# ---------------------------------------------------------------------------
# PostgreSQL persistence
# ---------------------------------------------------------------------------
+5
View File
@@ -23,6 +23,7 @@ from services.shared.logging import inject_trace_context, setup_logging
from services.shared.redis_keys import (
QUEUE_AGGREGATION,
QUEUE_RECOMMENDATION,
is_pipeline_enabled,
queue_key,
)
@@ -134,6 +135,10 @@ async def main() -> None:
try:
while True:
if not await is_pipeline_enabled(redis_client):
await asyncio.sleep(1)
continue
raw = await redis_client.lpop(queue)
if raw is None:
await asyncio.sleep(1)
+82 -1
View File
@@ -4,7 +4,7 @@ Computes TrendProjection objects by combining current trend momentum,
macro signal decay trajectories, and upcoming catalyst outlook.
Projections are persisted alongside trend_window records.
Requirements: 12.1, 12.2, 12.3, 12.4, 12.5, 12.9
Requirements: 12.1, 12.2, 12.3, 12.4, 12.5, 12.9, 13.1, 13.2, 13.3, 13.4, 13.5, 13.6
"""
from __future__ import annotations
@@ -126,6 +126,87 @@ def _direction_sign(direction: str) -> float:
return 0.0
# ---------------------------------------------------------------------------
# Exponentially weighted momentum (Requirements: 13.113.6)
# ---------------------------------------------------------------------------
def compute_ew_momentum(
strength_changes: list[float],
lambda_decay: float = 0.7,
) -> float:
"""Compute exponentially weighted momentum from historical strength changes.
Formula: M_t = Σ_{k=0}^{K-1} λ^k · ΔS_{t-k}
Normalized by geometric series sum Σ λ^k to produce value in [-1, 1].
When fewer than 2 historical cycles are available, returns 0.0
(caller should fall back to heuristic).
Args:
strength_changes: List of signed strength changes ΔS, most recent first.
Each value represents the change in signed trend strength from one
cycle to the next. Positive = strengthening bullish / weakening bearish.
lambda_decay: Decay factor λ (default 0.7). Must be in (0, 1).
Returns:
Normalized momentum in [-1, 1]. Returns 0.0 for empty or single-element lists.
Requirements: 13.1, 13.2, 13.3, 13.6
"""
if len(strength_changes) < 2:
return 0.0
# Use up to K=10 most recent changes, filtering out NaN values
k_max = min(len(strength_changes), 10)
changes = strength_changes[:k_max]
weighted_sum = 0.0
weight_sum = 0.0
for k, delta_s in enumerate(changes):
if math.isnan(delta_s):
continue
w = lambda_decay ** k
weighted_sum += w * delta_s
weight_sum += w
if weight_sum == 0.0:
return 0.0
normalized = weighted_sum / weight_sum
# Guard against NaN propagation
if math.isnan(normalized) or math.isinf(normalized):
return 0.0
return max(-1.0, min(1.0, normalized))
def compute_volatility_scaled_momentum(
momentum: float,
sigma_20: float,
) -> float:
"""Compute volatility-scaled momentum.
Formula: M_adj = M_t / max(σ_20, 0.01), clamped to [-2.0, 2.0].
Normalizes momentum relative to the ticker's typical price movement.
Args:
momentum: Raw or EW momentum value.
sigma_20: 20-day return standard deviation.
Returns:
Volatility-scaled momentum in [-2.0, 2.0].
Requirements: 13.4, 13.5
"""
denominator = max(sigma_20, 0.01)
scaled = momentum / denominator
# Guard against NaN propagation
if math.isnan(scaled) or math.isinf(scaled):
return 0.0
return max(-2.0, min(2.0, scaled))
# ---------------------------------------------------------------------------
# Macro signal decay projection
# ---------------------------------------------------------------------------
+170
View File
@@ -0,0 +1,170 @@
"""Regime detector for market regime classification.
Classifies the current market regime for each ticker based on
EMA trend indicators and volatility ratios. Adjusts scoring
thresholds and contradiction penalties per regime.
Requirements: 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.9
"""
from __future__ import annotations
import math
import statistics
from dataclasses import dataclass
from enum import Enum
class MarketRegime(str, Enum):
"""Market regime classification categories."""
TREND_FOLLOWING = "trend_following"
PANIC = "panic"
MEAN_REVERSION = "mean_reversion"
UNCERTAINTY = "uncertainty"
@dataclass(frozen=True)
class RegimeClassification:
"""Result of regime detection for a ticker."""
regime: MarketRegime
trend_indicator: float # R = sign(EMA_20 - EMA_100)
volatility_ratio: float # V_r = σ_20 / σ_100
bullish_threshold: float # Adjusted ±threshold for direction
bearish_threshold: float
contradiction_penalty_multiplier: float # 0.4 default, 0.6 for uncertainty
@dataclass(frozen=True)
class RegimeConfig:
"""Configuration parameters for regime detection."""
ema_short_period: int = 20
ema_long_period: int = 100
vol_short_period: int = 20
vol_long_period: int = 100
panic_vol_ratio: float = 1.5
trend_vol_ratio: float = 1.2
mean_reversion_vol_ratio: float = 1.0
default_threshold: float = 0.15
panic_threshold: float = 0.10
mean_reversion_threshold: float = 0.20
uncertainty_contradiction_multiplier: float = 0.6
# Default uncertainty classification used when data is insufficient
_DEFAULT_UNCERTAINTY = RegimeClassification(
regime=MarketRegime.UNCERTAINTY,
trend_indicator=0.0,
volatility_ratio=1.0,
bullish_threshold=0.15,
bearish_threshold=-0.15,
contradiction_penalty_multiplier=0.6,
)
def compute_ema(values: list[float], period: int) -> float:
"""Compute exponential moving average over the last ``period`` values.
Uses the standard EMA formula with multiplier = 2 / (period + 1).
Iterates through the values, seeding the EMA with the first value.
Raises ``ValueError`` when *values* is empty or *period* < 1.
"""
if not values or period < 1:
raise ValueError("values must be non-empty and period must be >= 1")
# Use only the last `period` values (or all if fewer)
data = values[-period:] if len(values) >= period else values
multiplier = 2.0 / (period + 1)
ema = data[0]
for value in data[1:]:
ema = (value - ema) * multiplier + ema
return ema
def _sign(x: float) -> float:
"""Return -1.0, 0.0, or 1.0 for the sign of *x*."""
if x > 0.0:
return 1.0
if x < 0.0:
return -1.0
return 0.0
def classify_regime(
closing_prices: list[float],
returns: list[float],
config: RegimeConfig = RegimeConfig(),
) -> RegimeClassification:
"""Classify market regime from price and return history.
Requires at least ``config.ema_long_period`` days of price history
for EMA_100. Falls back to UNCERTAINTY when data is insufficient
or standard deviations are zero.
Requirements: 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.9
"""
# Insufficient price data → uncertainty
if len(closing_prices) < config.ema_long_period:
return _DEFAULT_UNCERTAINTY
# Insufficient return data → uncertainty
if len(returns) < config.vol_long_period:
return _DEFAULT_UNCERTAINTY
# --- Trend indicator: R = sign(EMA_short - EMA_long) ---
ema_short = compute_ema(closing_prices, config.ema_short_period)
ema_long = compute_ema(closing_prices, config.ema_long_period)
trend_indicator = _sign(ema_short - ema_long)
# --- Volatility ratio: V_r = σ_short / σ_long ---
short_returns = returns[-config.vol_short_period:]
long_returns = returns[-config.vol_long_period:]
# Guard against zero or near-zero standard deviations
if len(short_returns) < 2 or len(long_returns) < 2:
return _DEFAULT_UNCERTAINTY
sigma_short = statistics.stdev(short_returns)
sigma_long = statistics.stdev(long_returns)
if sigma_long == 0.0 or sigma_short == 0.0:
return _DEFAULT_UNCERTAINTY
if math.isnan(sigma_short) or math.isnan(sigma_long):
return _DEFAULT_UNCERTAINTY
volatility_ratio = sigma_short / sigma_long
# --- Classification rules (Req 7.3) ---
# Panic takes priority: V_r > 1.5
if volatility_ratio > config.panic_vol_ratio:
regime = MarketRegime.PANIC
threshold = config.panic_threshold # ±0.10
contradiction_mult = 0.4
# Trend-following: R ≠ 0 AND V_r < 1.2
elif trend_indicator != 0.0 and volatility_ratio < config.trend_vol_ratio:
regime = MarketRegime.TREND_FOLLOWING
threshold = config.default_threshold # ±0.15
contradiction_mult = 0.4
# Mean-reversion: R = 0 AND V_r < 1.0
elif trend_indicator == 0.0 and volatility_ratio < config.mean_reversion_vol_ratio:
regime = MarketRegime.MEAN_REVERSION
threshold = config.mean_reversion_threshold # ±0.20
contradiction_mult = 0.4
# Uncertainty: all other cases
else:
regime = MarketRegime.UNCERTAINTY
threshold = config.default_threshold # ±0.15
contradiction_mult = config.uncertainty_contradiction_multiplier # 0.6
return RegimeClassification(
regime=regime,
trend_indicator=trend_indicator,
volatility_ratio=volatility_ratio,
bullish_threshold=threshold,
bearish_threshold=-threshold,
contradiction_penalty_multiplier=contradiction_mult,
)
+322 -16
View File
@@ -4,7 +4,7 @@ integration for aggregation.
Provides scoring functions used by the aggregation engine to weight
document intelligence signals when computing trend summaries.
Requirements: 6.1, 6.2, 6.5
Requirements: 2.12.6, 3.13.5, 4.24.3, 5.15.7, 6.16.5, 16.416.5
"""
from __future__ import annotations
@@ -14,6 +14,24 @@ from datetime import datetime, timezone
from services.shared.schemas import MarketContext
# ---------------------------------------------------------------------------
# Event type base rates for information gain computation (Req 3.1)
# ---------------------------------------------------------------------------
EVENT_TYPE_BASE_RATES: dict[str, float] = {
"earnings": 0.25,
"product_launch": 0.10,
"regulatory": 0.08,
"legal": 0.05,
"m_and_a": 0.03,
"management_change": 0.06,
"partnership": 0.12,
"market_expansion": 0.09,
"restructuring": 0.04,
"dividend": 0.15,
}
DEFAULT_BASE_RATE = 0.1
@dataclass(frozen=True)
class ScoringConfig:
@@ -62,6 +80,37 @@ class ScoringConfig:
volume_surge_threshold_pct: float = 50.0
volume_surge_boost: float = 0.15
# --- Probabilistic scoring parameters ---
# Toggle: when True, use probabilistic formulas (sigmoid gate,
# adaptive decay, info gain, regime multiplier, source accuracy).
# When False, preserve exact current heuristic behaviour.
probabilistic: bool = False
# Sigmoid gate parameters — smooth replacement for binary confidence gate.
# Gate value: σ(k·(x - midpoint)) where k = steepness.
sigmoid_steepness: float = 5.0
sigmoid_midpoint: float = 0.5
# Information gain parameters — surprise weighting for rare events.
# r = 1 + λ·(-log₂ P(event_type)), clamped to info_gain_max.
info_gain_lambda: float = 0.3
info_gain_max: float = 3.0
default_base_rate: float = 0.1
# Adaptive decay parameters — β scaling factors for event-specific
# half-life adjustment: τ_i = τ_base · (1+β_impact)·(1+β_surprise)·(1+β_market).
adaptive_decay_impact_scale: float = 1.0
adaptive_decay_surprise_scale: float = 1.0
adaptive_decay_market_scale: float = 0.5
# Regime multiplier parameters — replaces market context multiplier.
# M_regime = 1 + regime_return_weight·|z_r| + regime_volume_weight·|z_v|,
# clamped to [1.0, regime_multiplier_max].
regime_return_weight: float = 0.15
regime_volume_weight: float = 0.10
regime_multiplier_max: float = 2.5
# Singleton default config
DEFAULT_CONFIG = ScoringConfig()
@@ -77,6 +126,8 @@ def recency_weight(
reference_time: datetime,
window: str,
config: ScoringConfig = DEFAULT_CONFIG,
*,
half_life_override: float | None = None,
) -> float:
"""Compute an exponential recency decay weight for a document.
@@ -87,6 +138,8 @@ def recency_weight(
reference_time: The "now" anchor for the aggregation window (tz-aware).
window: One of the TrendWindow values (e.g. "7d").
config: Scoring parameters.
half_life_override: If provided, use this half-life instead of the
window-based default (used for adaptive decay).
Returns:
A weight in [config.min_recency_weight, 1.0].
@@ -102,7 +155,7 @@ def recency_weight(
return 1.0
age_hours = age_seconds / 3600.0
half_life = config.half_life_hours.get(window, 72.0)
half_life = half_life_override if half_life_override is not None else config.half_life_hours.get(window, 72.0)
weight = math.pow(2.0, -age_hours / half_life)
return max(weight, config.min_recency_weight)
@@ -170,6 +223,188 @@ def market_context_multiplier(
return 1.0 + boost
# ---------------------------------------------------------------------------
# Sigmoid confidence gate (Req 2.12.6)
# ---------------------------------------------------------------------------
def sigmoid_gate(
x: float,
steepness: float = 5.0,
midpoint: float = 0.5,
) -> float:
"""Smooth sigmoid confidence gate: σ(k·(x - midpoint)).
Replaces the binary 0/1 confidence gate in probabilistic mode.
Returns a value in (0, 1) — higher confidence produces higher gate.
Args:
x: Extraction confidence value, typically in [0, 1].
steepness: Steepness parameter k (default 5.0).
midpoint: Midpoint of the sigmoid transition (default 0.5).
Returns:
Gate value in (0, 1).
"""
z = steepness * (x - midpoint)
# Guard against overflow in exp for very negative z
if z < -500.0:
return 0.0
if z > 500.0:
return 1.0
return 1.0 / (1.0 + math.exp(-z))
# ---------------------------------------------------------------------------
# Information gain surprise weighting (Req 3.13.5)
# ---------------------------------------------------------------------------
def compute_info_gain(
event_type: str | None,
lambda_param: float = 0.3,
max_gain: float = 3.0,
default_base_rate: float = 0.1,
) -> float:
"""Compute information gain factor for an event type.
Formula: r = 1 + λ·(-log₂ P(event_type)), clamped to [1.0, max_gain].
Rarer events produce higher surprise weight. Unknown event types
use the default base rate.
Args:
event_type: Event type string (e.g. "earnings", "m_and_a").
lambda_param: Scaling parameter λ (default 0.3).
max_gain: Maximum clamp for the info gain factor (default 3.0).
default_base_rate: Fallback base rate for unknown event types.
Returns:
Information gain factor r in [1.0, max_gain].
"""
if event_type is None:
return 1.0
base_rate = EVENT_TYPE_BASE_RATES.get(event_type, default_base_rate)
# Guard against log₂(0) — base rates must be > 0
if base_rate <= 0.0:
base_rate = default_base_rate
if base_rate <= 0.0:
return 1.0
surprise = -math.log2(base_rate)
r = 1.0 + lambda_param * surprise
return min(max(r, 1.0), max_gain)
# ---------------------------------------------------------------------------
# Adaptive recency decay (Req 5.15.7)
# ---------------------------------------------------------------------------
def compute_adaptive_half_life(
base_half_life: float,
impact_score: float,
info_gain_factor: float,
market_multiplier: float,
config: ScoringConfig,
) -> float:
"""Compute adaptive half-life for event-specific recency decay.
Formula: τ_i = τ_base · (1 + β_impact) · (1 + β_surprise) · (1 + β_market)
The adaptive half-life is always >= base_half_life (decay is never faster).
Args:
base_half_life: Fixed half-life for the window (hours).
impact_score: Signal impact score in [0, 1].
info_gain_factor: Information gain factor r in [1.0, 3.0].
market_multiplier: Market context/regime multiplier in [1.0, ~2.5].
config: Scoring config with adaptive decay scale parameters.
Returns:
Adaptive half-life in hours, >= base_half_life.
"""
# β_impact: impact_score scaled linearly 0→0, 1→adaptive_decay_impact_scale
beta_impact = impact_score * config.adaptive_decay_impact_scale
# β_surprise: info_gain_factor scaled linearly r=1→0, r=3→adaptive_decay_surprise_scale
beta_surprise = ((info_gain_factor - 1.0) / 2.0) * config.adaptive_decay_surprise_scale
# β_market: market_multiplier scaled linearly 1.0→0, 1.45→adaptive_decay_market_scale
if market_multiplier > 1.0:
beta_market = ((market_multiplier - 1.0) / 0.45) * config.adaptive_decay_market_scale
else:
beta_market = 0.0
tau = base_half_life * (1.0 + beta_impact) * (1.0 + beta_surprise) * (1.0 + beta_market)
# Ensure adaptive half-life is never less than base (Property 5)
return max(tau, base_half_life)
# ---------------------------------------------------------------------------
# Regime multiplier (Req 6.16.5)
# ---------------------------------------------------------------------------
def compute_regime_multiplier(
returns: list[float] | None,
volumes: list[float] | None,
config: ScoringConfig = DEFAULT_CONFIG,
) -> float:
"""Compute regime-aware multiplier from return and volume z-scores.
Formula: M_regime = 1 + 0.15·|z_r| + 0.10·|z_v|, clamped to [1.0, max].
Args:
returns: List of recent daily returns (at least 20 values for z-score).
volumes: List of recent daily volumes (at least 20 values for z-score).
config: Scoring config with regime multiplier parameters.
Returns:
Regime multiplier in [1.0, config.regime_multiplier_max].
"""
if not returns or len(returns) < 2:
return 1.0
# Filter out NaN values from returns
clean_returns = [r for r in returns if not math.isnan(r)]
if len(clean_returns) < 2:
return 1.0
# Return z-score: z_r = (r_t - μ_20) / σ_20
r_window = clean_returns[-20:] if len(clean_returns) >= 20 else clean_returns
r_t = clean_returns[-1]
mu_r = sum(r_window) / len(r_window)
var_r = sum((x - mu_r) ** 2 for x in r_window) / len(r_window)
sigma_r = math.sqrt(var_r)
z_r = 0.0
if sigma_r > 0.0:
z_r = (r_t - mu_r) / sigma_r
# Volume z-score: z_v = (log(V_t) - μ_V) / σ_V
z_v = 0.0
if volumes and len(volumes) >= 2:
clean_volumes = [v for v in volumes if not math.isnan(v)]
if len(clean_volumes) >= 2:
v_window = clean_volumes[-20:] if len(clean_volumes) >= 20 else clean_volumes
# Use log-volumes, guard against zero/negative volumes
log_vols = [math.log(max(v, 1.0)) for v in v_window]
log_v_t = math.log(max(clean_volumes[-1], 1.0))
mu_v = sum(log_vols) / len(log_vols)
var_v = sum((x - mu_v) ** 2 for x in log_vols) / len(log_vols)
sigma_v = math.sqrt(var_v)
if sigma_v > 0.0:
z_v = (log_v_t - mu_v) / sigma_v
m_regime = 1.0 + config.regime_return_weight * abs(z_r) + config.regime_volume_weight * abs(z_v)
# Guard against NaN propagation from upstream data
if math.isnan(m_regime) or math.isinf(m_regime):
return 1.0
return max(1.0, min(m_regime, config.regime_multiplier_max))
# ---------------------------------------------------------------------------
# Combined document signal weight
# ---------------------------------------------------------------------------
@@ -186,6 +421,12 @@ class SignalWeight:
market_ctx_multiplier: float # >= 1.0
combined: float
# New optional fields for probabilistic mode
sigmoid_gate: float | None = None # Smooth gate value [0, 1]
info_gain_factor: float = 1.0 # Surprise multiplier
source_accuracy_factor: float = 1.0 # Historical accuracy multiplier
regime_multiplier: float | None = None # M_regime replacing M_context
def compute_signal_weight(
published_at: datetime,
@@ -196,18 +437,23 @@ def compute_signal_weight(
extraction_confidence: float = 0.5,
market_ctx: MarketContext | None = None,
config: ScoringConfig = DEFAULT_CONFIG,
*,
event_type: str | None = None,
impact_score: float = 0.5,
source_accuracy_factor: float = 1.0,
returns: list[float] | None = None,
volumes: list[float] | None = None,
) -> SignalWeight:
"""Compute the combined aggregation weight for a single document signal.
The formula is:
When ``config.probabilistic`` is False (default), the formula is:
combined = confidence_gate * recency * credibility
* (1 + novelty_bonus) * market_ctx_multiplier
where novelty_bonus = novelty_score * config.novelty_bonus_max
and market_ctx_multiplier >= 1.0 based on volatility/volume features.
Documents with extraction_confidence below config.confidence_floor
receive a combined weight of 0.0 (gated out).
When ``config.probabilistic`` is True, the formula is:
combined = sigmoid_gate * recency(adaptive) * credibility
* (1 + novelty_bonus) * info_gain * source_accuracy
* regime_multiplier
Args:
published_at: Document publication time.
@@ -218,27 +464,82 @@ def compute_signal_weight(
extraction_confidence: Extraction confidence from the model (0-1).
market_ctx: Optional market context features for the symbol.
config: Scoring parameters.
event_type: Optional event type for information gain computation.
impact_score: Signal impact score in [0, 1] (default 0.5).
source_accuracy_factor: Historical source accuracy factor (default 1.0).
returns: Optional list of recent daily returns for regime multiplier.
volumes: Optional list of recent daily volumes for regime multiplier.
Returns:
A ``SignalWeight`` with the component breakdown and combined score.
"""
# Confidence gate
gate = 1.0 if extraction_confidence >= config.confidence_floor else 0.0
rec = recency_weight(published_at, reference_time, window, config)
cred = credibility_weight(source_credibility, config)
bonus = novelty_score * config.novelty_bonus_max
mkt_mult = market_context_multiplier(market_ctx, config)
combined = gate * rec * cred * (1.0 + bonus) * mkt_mult
if not config.probabilistic:
# --- Heuristic mode: preserve exact current formula ---
gate = 1.0 if extraction_confidence >= config.confidence_floor else 0.0
rec = recency_weight(published_at, reference_time, window, config)
mkt_mult = market_context_multiplier(market_ctx, config)
combined = gate * rec * cred * (1.0 + bonus) * mkt_mult
return SignalWeight(
recency=rec,
credibility=cred,
novelty_bonus=bonus,
confidence_gate=gate,
market_ctx_multiplier=mkt_mult,
combined=combined,
)
# --- Probabilistic mode ---
# 1. Sigmoid confidence gate (Req 2.12.5)
sg = sigmoid_gate(extraction_confidence, config.sigmoid_steepness, config.sigmoid_midpoint)
# 2. Information gain factor (Req 3.13.5)
ig = compute_info_gain(
event_type,
lambda_param=config.info_gain_lambda,
max_gain=config.info_gain_max,
default_base_rate=config.default_base_rate,
)
# 3. Regime multiplier (Req 6.16.5) — replaces market_context_multiplier
rm = compute_regime_multiplier(returns, volumes, config)
# 4. Adaptive recency decay (Req 5.15.7)
base_half_life = config.half_life_hours.get(window, 72.0)
adaptive_hl = compute_adaptive_half_life(
base_half_life=base_half_life,
impact_score=impact_score,
info_gain_factor=ig,
market_multiplier=rm,
config=config,
)
rec = recency_weight(
published_at, reference_time, window, config,
half_life_override=adaptive_hl,
)
# 5. Source accuracy factor (Req 4.24.3)
saf = source_accuracy_factor
# 6. Combined weight
combined = sg * rec * cred * (1.0 + bonus) * ig * saf * rm
return SignalWeight(
recency=rec,
credibility=cred,
novelty_bonus=bonus,
confidence_gate=gate,
market_ctx_multiplier=mkt_mult,
confidence_gate=sg, # sigmoid gate value in probabilistic mode
market_ctx_multiplier=rm, # regime multiplier stored here for compat
combined=combined,
sigmoid_gate=sg,
info_gain_factor=ig,
source_accuracy_factor=saf,
regime_multiplier=rm,
)
@@ -256,6 +557,11 @@ class WeightedSignal:
sentiment_value: float # numeric sentiment: +1 positive, -1 negative, 0 neutral/mixed
impact_score: float
# New optional fields for probabilistic mode
info_gain_factor: float = 1.0 # r = 1 + λ·(-log₂ P(event_type))
source_accuracy_factor: float = 1.0 # [0.5, 1.5] from historical accuracy
adaptive_half_life: float | None = None # τ_i when adaptive decay is active
def sentiment_to_numeric(sentiment: str) -> float:
"""Map a sentiment label to a signed numeric value."""

Some files were not shown because too many files have changed in this diff Show More