Commit Graph

42 Commits

Author SHA1 Message Date
Celes Renata 7c23c044d7 feat: agent variants — migration, API, service integration, frontend, tests
- Migration 027: agent_variants table with single-active enforcement,
  variant_id column on agent_performance_log
- API: full CRUD, clone from agent/variant, activate/deactivate,
  per-variant performance metrics and history endpoints
- Services: extractor, event classifier, thesis rewriter all wired
  to AgentConfigResolver with variant override support
- Frontend: variant list, comparison view, create/edit/clone forms,
  activate/delete actions on Agents page
- Tests: API tests + 5 property-based tests (single-active invariant,
  clone preservation, config resolution, slug determinism, update idempotence)
- Spec files for agent-variants feature
2026-04-17 05:15:42 +00:00
Celes Renata 734bf001a7 feat: risk tier selector on Trading page + confidence filter on Recommendations
- Trading page: added conservative/moderate/aggressive selector that
  updates the trading engine config via PUT /api/trading/config
- Recommendations page: added risk tier dropdown that defaults to the
  engine's current tier and filters recs by the tier's min_confidence
- Backend: added min_confidence query param to GET /api/recommendations
- Risk tier thresholds: conservative ≥0.75, moderate ≥0.55, aggressive ≥0.40
2026-04-17 05:08:54 +00:00
Celes Renata fd862da29e fix: remove broken capital controls, reset now queries broker for real balance
- Removed PUT /api/trading/capital (set capital) — only touched in-memory state
- Removed POST /api/trading/capital/adjust (add/withdraw) — same problem
- Reset endpoint now: liquidates Alpaca positions, cancels orders, clears DB,
  then queries Alpaca for real portfolio_value to set engine capital
- Frontend: replaced CapitalCard with simple ResetCard (one button)
- Removed useSetTradingCapital and useAdjustCapital hooks
2026-04-17 04:24:10 +00:00
Celes Renata 90614dd7bb feat: paper trading capital controls — add, withdraw, and full reset
Three distinct capital operations on the Trading Controls page:

- Set Capital: overwrites pool balances to a new amount (existing)
- Add/Withdraw: adjusts active pool by a delta without touching
  positions, orders, or history. Validates sufficient balance for
  withdrawals. Logged to reserve_pool_ledger as manual_adjustment.
- Reset Everything: nuclear option — deletes all positions, orders,
  trading decisions, stop levels, snapshots, backtests, notifications,
  and circuit breaker events, then resets capital fresh. Red button
  with double-confirmation dialog.

Backend: POST /api/trading/capital/adjust and POST /api/trading/reset
Frontend: CapitalCard rebuilt with three sections and confirmation UIs
2026-04-17 02:23:26 +00:00
Celes Renata 45752b9a29 feat: AI Agents management page with per-agent performance tracking
New Agents tab in the sidebar (Ops group) for viewing, editing, and
creating AI agent configurations:

Database (migration 026):
- ai_agents table: editable configs for each LLM agent (model, prompts,
  temperature, tokens, retries). source='system' for built-in,
  source='user' for custom. Seeds 3 system agents (Document Extractor,
  Event Classifier, Thesis Rewriter) using WHERE NOT EXISTS to never
  overwrite user edits across reinstalls.
- agent_performance_log table: per-invocation metrics (duration,
  confidence, retries, tokens, errors) linked to agent config.

API endpoints:
- GET/POST /api/agents — list and create agents
- GET/PUT/DELETE /api/agents/{id} — view, edit, delete (system agents
  can be edited but not deleted)
- GET /api/agents/{id}/performance — aggregated metrics (success rate,
  avg/p95 latency, confidence, token usage)
- GET /api/agents/{id}/performance/history — hourly time series

Frontend:
- AgentsPage with sidebar list + detail panel
- Agent detail: config display, system prompt viewer, performance
  dashboard with metrics cards and time-series chart
- Edit form: all config fields editable including system prompt,
  model, temperature, tokens, retries
- Create form: new user-defined agents with auto-slug generation
- System agents show blue badge, user agents show green badge
2026-04-17 01:24:35 +00:00
Celes Renata 2360c501e4 feat: intraday hourly price bars via Polygon range endpoint
- New 'intraday_bars' endpoint in PolygonMarketAdapter: fetches hourly
  bars for today using range_bars URL with timespan=hour, sort=asc
- Scheduler expands intraday_bars global source into per-ticker jobs
  for all active companies (every 15 minutes via polling_interval)
- Migration 025 inserts the intraday source with 900s cadence
- Frontend price matching uses closest-timestamp instead of date-string
  matching, with 2h tolerance for intraday and 36h for daily windows
- Bumped market price fetch limit to 200 for intraday granularity
2026-04-17 01:13:24 +00:00
Celes Renata c4206b3f4c feat: overlay stock price on trend charts with right Y axis
- New GET /api/market/prices/{ticker} endpoint serving OHLCV data from
  market_snapshots, deduped by bar_timestamp
- New useMarketPrices hook in frontend
- Trend chart now shows price (purple line) on a right Y axis ($)
  alongside trend metrics (%) on the left Y axis
- Custom tooltip formats price as dollars, metrics as percentages
- Price line uses connectNulls for days with missing bar data
2026-04-17 01:09:36 +00:00
Celes Renata ebe0ccca4c fix: trend chart tooltip shows no data on hover
Replaced Recharts default Tooltip with formatter prop (broken in
Recharts v3 with explicit type annotations) with a custom
TrendTooltip component matching the SQL Explorer pattern. Shows
each series name, value, and color on hover.
2026-04-17 01:01:02 +00:00
Celes Renata 5593ee6d92 fix: company detail crash — patterns API returns object not array
/api/patterns/{ticker} returns {ticker, patterns, count} but
useHistoricalPatterns typed its response as HistoricalPattern[].
The .map() call on the object caused 'e.map is not a function'.
Fixed by unwrapping resp.patterns in the hook's queryFn.
2026-04-17 00:50:51 +00:00
Celes Renata 7c589353f8 fix: blank company charts + competitor GUIDs instead of tickers
Trend charts blank:
- trend_windows uses upsert (1 row per ticker/window), so charts had
  at most 1 data point. Added trend_history table (migration 024) that
  appends every snapshot. New /api/trends/history endpoint serves the
  time series. Frontend now uses useTrendHistory for charts and
  useTrends for the latest summary card.

Competitor GUIDs:
- list_competitors query returned raw company_b_id UUIDs without
  joining companies table. Added LEFT JOIN with CASE to resolve the
  other company's ticker and legal_name. Updated Pydantic model to
  include enriched fields. Frontend fallback changed from truncated
  UUID to ticker/legal_name/Unknown.
2026-04-17 00:42:55 +00:00
Celes Renata f2d8744a4f fix: backtest submission shows no results — 4 bugs fixed
- ID mismatch: API generated a throwaway UUID while BacktestReplay
  generated its own internally. Frontend polled with wrong ID and
  never found the DB row. Now pre-generate ID in endpoint and pass
  it to BacktestReplay.
- Field name: API returned 'backtest_id' but frontend read 'data.id'.
  Unified to 'id' everywhere.
- No polling: useBacktestResult fired once and never refreshed.
  Added refetchInterval that polls every 2s while status is running.
- Response shape: GET endpoint nested results under 'result' object
  but frontend expected flat fields. Flattened response to match
  BacktestResult type.
- Added running/failed/completed status indicators in BacktestPanel.
2026-04-17 00:31:17 +00:00
Celes Renata 63287903d0 feat: wire up stop levels, circuit breaker daily loss, profit-taking, real portfolio/decisions/history endpoints 2026-04-16 15:52:46 +00:00
Celes Renata 58a8726306 feat: add paper trading capital controls — API endpoint + UI with presets, fix status/metrics to read real state, fix migration duplicates 2026-04-16 14:06:30 +00:00
Celes Renata c5e9644f6f fix: guard EventSource for jsdom test env, add rate-limits MSW handler 2026-04-16 08:19:53 +00:00
Celes Renata 58a05ca322 feat: add SSE stream for live pipeline status, add all 10 queues + DLQs, configure nginx for SSE 2026-04-16 08:15:44 +00:00
Celes Renata 0b1640abb9 feat: add status colors for document pipeline stages, add status filter to documents page 2026-04-16 08:06:12 +00:00
Celes Renata cdc825619e feat: add live queue depths to pipeline health API and dashboard 2026-04-16 07:49:07 +00:00
Celes Renata 0ee7f26633 feat: raise market_api rate to 20/min, add global Polygon cap at 45/min, add rate-limit API + watchlist warning 2026-04-16 07:26:10 +00:00
Celes Renata 1ccea17600 fix: tooltip type inference for Recharts strict mode 2026-04-16 06:01:29 +00:00
Celes Renata 79a85723b6 feat: rich tooltips in SQL Explorer charts show all row values
Hover over any bar, line point, or scatter dot to see every column
value for that data point. The Y-axis column is highlighted in
brand color, X-axis in white, and other columns in gray. Works
for all chart types (bar, line, scatter, auto).
2026-04-16 05:57:06 +00:00
Celes Renata b43ad88f5d feat: auto-chart detection in SQL Explorer
Adds an ' Auto' button that analyzes query results and picks the
best chart type and column mapping:

- Date/time column + numeric → line chart (time series)
- Categorical + numeric → bar chart (categories)
- Two numeric columns → scatter plot
- Shows detected type and column names as a label

Click Auto, run any query, and it figures out the rest.
2026-04-16 05:52:41 +00:00
Celes Renata 328cb0de28 fix: SQL Explorer chart parses string values as floats
The pg-query API returns all values as strings. The chart builder
was using Number() which returns NaN for non-numeric strings.
Now uses parseFloat with NaN fallback to 0.
2026-04-16 05:33:53 +00:00
Celes Renata 1107d34027 fix: SQL Explorer handles comments and shows descriptive errors
- Strip SQL comments (-- and /* */) before checking for SELECT,
  so queries with leading comments don't get rejected
- Show the actual error detail from the API response instead of
  generic 'API error 400' in the SQL Explorer UI
2026-04-16 05:25:45 +00:00
Celes Renata e652a62dbc fix: Trading Controls page field mapping for macro/competitive status
The API returns macro_enabled/competitive_enabled but the TypeScript
interfaces expected 'enabled'. The toggles always showed disabled.
Now handles both field names with fallback.
2026-04-16 01:46:13 +00:00
Celes Renata 36c92196d2 fix: remove unused Legend import from Dashboards (TS strict) 2026-04-16 01:11:23 +00:00
Celes Renata 949324dc89 feat: SQL Explorer with PostgreSQL schema browser and pre-built queries
The SQL Explorer was querying Trino which has zero tables. Rewrote to
use PostgreSQL directly:

Backend:
- GET /api/analytics/pg-schema: returns all public tables with column
  names, types, and nullability from information_schema
- POST /api/analytics/pg-query: read-only SQL execution against
  PostgreSQL with SELECT-only enforcement, auto LIMIT, and descriptive
  error messages for syntax/table/query errors

Frontend:
- Schema browser shows all PostgreSQL tables with columns and types
- Click a table name → generates SELECT * FROM table LIMIT 100
- Pre-built Queries section with 12 seeded queries covering companies,
  recommendations, trends, market prices, documents, global events,
  trading decisions, ingestion health, reserve pool, sector exposure
- User-saved queries shown separately with delete buttons
- Chart builder, Monaco editor, and save functionality preserved

Migration 021: seeds 12 pre-built saved queries
2026-04-16 01:06:49 +00:00
Celes Renata 55512ca5a8 fix: rewrite dashboards to use PostgreSQL API instead of empty Trino lakehouse
The Trino/Iceberg lakehouse has zero tables, so all Trino-backed
dashboards showed 'No data available'. Rewrote all four to use
existing PostgreSQL-backed API endpoints:

- Sentiment Heatmap: useTrends + useCompanies → sector and ticker
  trend strength bar charts (30k trend_windows in DB)
- Prediction Accuracy: useRecommendations → confidence distribution
  and action distribution charts (30k recommendations in DB)
- Paper PnL: useTradingMetrics + useTradingMetricsHistory → equity
  curve, daily returns, win/loss stats from trading engine
- Model Quality: useModelPerformance + useModelFailures → success
  rate, latency, retries, and failure table from ops API

Removed unused Trino query function and ScatterChart imports.
2026-04-16 00:58:18 +00:00
Celes Renata b5c0c6d7c9 fix: aggregate ingestion throughput chart by time bucket
The throughput API returns one row per source_type per time bucket,
but the chart was mapping each row as a separate bar. With 5 source
types × 24 hours, the bars were tiny and overlapping. Now aggregates
completed/failed/items across source types per time bucket so the
chart shows meaningful totals.
2026-04-16 00:52:29 +00:00
Celes Renata c4b90a5224 fix: sidebar nav highlights both Trading Controls and Trading Engine
When on /trading/engine, the /trading nav item also matched via
startsWith. Now checks if a more specific child route matches
first and uses exact match in that case.
2026-04-15 20:07:31 +00:00
Celes Renata 516731e69a fix: remove explicit type annotations on Recharts formatter callbacks
TypeScript strict mode in CI rejects explicit parameter types on
Recharts formatter/tickFormatter callbacks. Use inference with
'as number' casts on the value instead. Also fix unsafe cast in
PortfolioComposition and handle possibly-undefined percent.
2026-04-15 16:17:00 +00:00
Celes Renata 4ffde8cc06 feat: autonomous trading engine — full implementation
- Database migration 018 with 13 tables for trading engine state
- Trading engine service (services/trading/) with 12 pure computation modules:
  position sizer, stop-loss manager, reserve pool, circuit breaker,
  risk tier controller, correlation matrix, tax lots, trading window,
  gradual entry, notifications, micro-trading, backtester
- Core TradingEngine with pre-trade evaluation pipeline and integration wiring
- FastAPI HTTP service with 14 endpoints (health, config, decisions, metrics, backtest)
- Performance tracker with Sharpe ratio, drawdown, profit factor computation
- 194 Python tests (165 property-based + 29 integration)
- Frontend: 13 TanStack Query hooks, 7 dashboard panels, tabbed Trading Engine page
- Helm chart entry, network policy, nginx proxy, ingress for trading-engine
- Shared infrastructure: enums, Redis keys, TradingConfig in AppConfig
2026-04-15 16:12:22 +00:00
Celes Renata 86808465de fix: remove explicit type annotations on Recharts callbacks for v3 compat 2026-04-14 20:40:31 +00:00
Celes Renata 916aaff9f3 feat: add trend history chart with strength/confidence/contradiction time series 2026-04-14 20:37:25 +00:00
Celes Renata 2a96c8338b fix: remove unused StatusBadge import in GlobalEvents.tsx 2026-04-14 19:53:40 +00:00
Celes Renata 4e191957b4 fix: remove duplicate closing tag in CompanyDetail.tsx 2026-04-14 19:50:53 +00:00
Celes Renata f7a11d14ea feat: competitive intelligence & historical pattern matching layer 2026-04-14 19:42:48 +00:00
Celes Renata 99e17be282 phase 16: fix env var fallback - use || instead of ?? for empty string 2026-04-11 20:06:13 -07:00
Celes Renata 4d0c38bba7 phase 16: vitest + MSW frontend tests, CI integration 2026-04-11 19:28:38 -07:00
Celes Renata 6f5b2231a2 phase 16: add registry/risk nginx proxies, add company form, network policies 2026-04-11 19:12:07 -07:00
Celes Renata 59da3fe89e phase 16: nginx-unprivileged on 8080, helm dashboard deployment 2026-04-11 16:37:59 -07:00
Celes Renata 1fcb79503e phase 16: fix TS strict mode errors, node 24, update steering docs 2026-04-11 16:35:50 -07:00
Celes Renata faccb0b8db phase 16: React dashboard with full platform control and analytics 2026-04-11 16:19:46 -07:00