MarginWatch — AI Agent Observability Dashboard
A self-contained AI agent observability dashboard demonstrating real-time data ingestion, structured Claude Sonnet output, anomaly alerting, and multi-signal evaluation. Built as a single-file HTML application with zero backend dependencies — deployable to any static host in under two minutes. Proves the pattern: configurable threshold monitoring, a pattern detection engine, and a Claude-powered evaluation agent that returns structured analysis on demand.
Core Technologies
Architecture Components
- Single-file HTML/JS/CSS — no build step, no framework dependency, deployable anywhere static files are served
- Chart.js for all data visualisation: price + MA chart, business margins, revenue/EPS dual-axis, volume bars
- Candlestick renderer built in vanilla JS — 20-session bull/bear/doji pattern detection with signal classification
- Claude Sonnet AI agent layer — structured 4-point evaluation on demand with deterministic fallback
- Configurable alert engine with seven thresholds across four trigger modes: % change, floor breach, volume spike, AI anomaly flag
- Scheduled review cadence selector (weekly / monthly / quarterly) with next-review date tracking
- Event log with timestamped entries for all state changes and evaluations
- Live data swap point: simulateTick() is the integration hook — replace with any financial API feed
Problem
Business owners and investors monitoring equity positions alongside company fundamentals typically work across three or four disconnected tools — a charting platform for price and technicals, a spreadsheet for margin tracking, a separate earnings tracker for EPS and P/E, and manual calendar reminders for review cadence. None of these talk to each other, none apply configurable alert logic, and none provide AI-driven synthesis of the full picture at a glance.
- Margin compression is often identified at month-end close rather than as it happens — by which time corrective action is reactive rather than pre-emptive.
- Volume anomalies on equity positions go unnoticed without a dedicated screening tool running alongside business metrics.
- P/E ceiling breaches and EPS floor violations have no automated flag in standard portfolio views — they require manual calculation on each review.
Solution
A unified monitoring layer that holds business margins, equity metrics, and technical signals in one state object, evaluates all of them against configurable thresholds on every data tick, and routes the full snapshot to Claude Sonnet for structured analysis when requested.
- Seven alert thresholds — gross margin floor, operating margin floor, net margin floor, EPS floor, P/E ceiling, % change trigger, volume spike multiplier — all adjustable via sliders with live re-evaluation.
- Candlestick pattern engine classifies the last three sessions as bullish, bearish, or neutral based on open/close relationships and doji detection, surfaced as a metric card and in the alert panel.
- Moving average crossover detection compares MA20 and MA50 to current price and flags golden cross or death cross conditions automatically.
- AI evaluation prompt constructed from the live state — price, margins, EPS, P/E, volume ratio, MA positions, candlestick signal — returning a 4-point structured assessment with a recommended action.
Outcome
A deployable financial intelligence tool that consolidates seven metric categories, four alert modes, and an AI evaluation layer into a single 48KB file with no external dependencies beyond Chart.js and the Anthropic API.
- Full alert pipeline operational: threshold breach → floor violation → volume spike → AI anomaly flag, all firing independently and surfacing in the alert panel.
- Candlestick pattern recognition across 20 sessions with bull/bear/doji classification and 3-candle sequence detection.
- AI agent evaluation structured as 4-point analysis: margin health → valuation & EPS → technical signal → recommended action.
- Deployable to AWS S3 + CloudFront in under two minutes — single file, no build pipeline required.
Key Learnings & Decisions
Dashboard Architecture
- Single-file architecture is the right choice for a standalone financial tool — it eliminates deployment complexity, makes the integration surface explicit (one swap point for live data), and keeps the codebase auditable by anyone reviewing it.
- Chart.js dual-axis configuration for the revenue/EPS chart required explicit yAxisID assignment on both datasets and a right-side axis definition — the default single-axis assumption silently drops the second series without error.
- Candlestick rendering in vanilla JS is cleaner than importing a charting library for a single component — absolute positioning within a fixed-height container gives precise control over wick and body geometry.
AI Agent Design
- Constructing the AI evaluation prompt from live state rather than hardcoded descriptions means the agent always reflects current readings — it cannot hallucinate stale data because the data is injected at call time.
- Structured 4-point output format (margin health / valuation / technical / action) is more actionable than a free-form summary — it forces the model to address each category explicitly and gives the reader a predictable reading pattern.
- A deterministic fallback evaluation built from the same state object ensures the dashboard remains fully functional if the Anthropic API is unavailable — the fallback uses the same logic the prompt describes, so outputs are consistent.
Alert System
- Threshold sliders with live re-evaluation on every oninput event give immediate feedback on how threshold changes affect the current alert state — more useful than a save-and-recalculate pattern for a monitoring tool.
- Unusual volume detection based on a rolling 12-period average is more robust than a fixed absolute threshold — it adapts to the stock's current trading regime rather than becoming stale as average volumes shift.
Implementation Milestones
A breakdown of the key tasks and milestones that brought this project to life.
Dashboard Core
CompleteSingle-file HTML application with Chart.js visualisations, metric cards, and state management.
Key Tasks Completed
Price chart with MA20 / MA50 overlay and crossover detection
Chart.js line chart with moving average datasets and golden/death cross badge detection.
Business margin quarterly trend chart (gross, operating, net)
Three-dataset line chart with per-series colour coding and dashed line styles.
Revenue + EPS dual-axis chart
Bar + line combo with explicit yAxisID on both datasets — required to prevent silent dataset drop on single-axis default.
Volume bar chart with unusual volume highlighting
Rolling 12-period average used as dynamic threshold; unusual bars highlighted amber.
Alert Engine
CompleteSeven configurable thresholds with four trigger modes — % change, floor breach, volume spike, AI flag.
Key Tasks Completed
Slider-driven threshold configuration with live re-evaluation
oninput events trigger runChecks() on every slider change — immediate feedback without a save step.
Alert panel rendering with severity levels
Critical / warning / info / ok levels rendered with colour-coded badges in the alert panel.
Scheduled review cadence selector with next-review date calculation
Weekly / monthly / quarterly buttons update next-review date in the header.
Candlestick & Technical Analysis
Complete20-session candlestick renderer with bull/bear/doji classification and pattern detection.
Key Tasks Completed
Vanilla JS candlestick renderer with wick and body geometry
Absolute positioning within a fixed-height container for precise wick and body placement — no library import required.
3-candle sequence pattern detection
Last 3 candles classified as bullish momentum, bearish pressure, or doji — surfaced in the rating badge and alert panel.
Moving average crossover detection (golden cross / death cross)
MA20 and MA50 computed from price history; crossover condition checked against current price on every tick.
AI Evaluation Layer
CompleteClaude Sonnet integration with structured 4-point evaluation and deterministic fallback.
Key Tasks Completed
Live state-to-prompt construction
All current readings injected at evaluation time — agent cannot reference stale data.
Structured 4-point output format
Margin health / valuation / technical / recommended action — predictable reading pattern for every evaluation.
Deterministic fallback evaluation
Fallback uses the same threshold logic as the prompt — consistent outputs whether API is available or not.
Deployment
CompleteSingle-file deployment to static host. Live at /margin-watch.html and case study at /projects/margin-watch/.
Key Tasks Completed
Portfolio case study page published
Case study live at adventuringghost.com/projects/margin-watch/.
Standalone tool URL published
Dashboard live at /margin-watch.html — single file, no build pipeline required.
Monitoring & Analysis
Alert Engine
Seven configurable thresholds evaluated on every data tick — gross margin floor, operating margin floor, net margin floor, EPS floor, P/E ceiling, % change trigger, and volume spike multiplier. Each threshold breach surfaces immediately in the alert panel with a severity level (critical / warning / info / ok).
AI Agent Evaluation Log
Every agent evaluation is timestamped in the event log. The AI constructs its assessment from the live state snapshot at call time — all readings are injected into the prompt, not hardcoded — ensuring the evaluation always reflects current data.